before_code
stringlengths
14
465k
reviewer_comment
stringlengths
16
64.5k
after_code
stringlengths
9
467k
diff_context
stringlengths
0
97k
file_path
stringlengths
5
226
comment_line
int32
0
26
language
stringclasses
37 values
quality_score
float32
0.07
1
comment_type
stringclasses
9 values
comment_length
int32
16
64.5k
before_lines
int32
1
17.2k
after_lines
int32
1
12.1k
is_negative
bool
2 classes
pr_title
stringlengths
1
308
pr_number
int32
1
299k
repo_name
stringclasses
533 values
repo_stars
int64
321
419k
repo_language
stringclasses
27 values
reviewer_username
stringlengths
0
39
author_username
stringlengths
2
39
toggle.value = false return () => h('span') }, } const App = { setup() { return () => h( Suspense, {}, { default: () => [ h('main', {}, [ h(AsyncWrapper, { prop:...
No issues found.
toggle.value = false return () => h('span') }, } const App = { setup() { return () => h( Suspense, {}, { default: () => [ h('main', {}, [ h(AsyncWrapper, { prop:...
@@ -2357,6 +2357,30 @@ describe('SSR hydration', () => { expect(`Hydration style mismatch`).not.toHaveBeenWarned() }) + test('with disabled teleport + undefined target', async () => { + const container = document.createElement('div') + const isOpen = ref(false) + const App = { + s...
packages/runtime-core/__tests__/hydration.spec.ts
0
TypeScript
1
none
16
51
51
true
fix(Teleport): hydrate disabled Teleport with undefined target
11,235
vuejs/vue-next
25,296
TypeScript
linzhe141
() => new Promise<typeof CompDef>(res => res(CompDef as any)), ), ) customElements.define('my-async-el-props-emits', E) container.innerHTML = `<my-async-el-props-emits id="my_async_el_props_emits"></my-async-el-props-emits>` const e = container.childNodes[0] as VueElement ...
No issues found.
() => new Promise<typeof CompDef>(res => res(CompDef as any)), ), ) customElements.define('my-async-el-props-emits', E) container.innerHTML = `<my-async-el-props-emits id="my_async_el_props_emits"></my-async-el-props-emits>` const e = container.childNodes[0] as VueElement ...
@@ -1,5 +1,6 @@ import type { MockedFunction } from 'vitest' import { + type HMRRuntime, type Ref, type VueElement, createApp, @@ -15,6 +16,8 @@ import { useShadowRoot, } from '../src' +declare var __VUE_HMR_RUNTIME__: HMRRuntime + describe('defineCustomElement', () => { const container = document...
packages/runtime-dom/__tests__/customElement.spec.ts
0
TypeScript
1
none
16
51
51
true
feat(custom-element): inject child components styles to custom element shadow root
11,517
vuejs/vue-next
25,296
TypeScript
yyx990803
const root = document.createElement('div') const Child: FunctionalComponent = (_, { slots }) => slots.default!() const App = { setup() { useCssVars(() => state) return () => h(Child, null, () => value.value ? [h('div')] : [h('div'), h('div')], ) ...
No issues found.
const root = document.createElement('div') const Child: FunctionalComponent = (_, { slots }) => slots.default!() const App = { setup() { useCssVars(() => state) return () => h(Child, null, () => value.value ? [h('div')] : [h('div'), h('div')], ) ...
@@ -385,6 +385,44 @@ describe('useCssVars', () => { } }) + test('with delay mount child', async () => { + const state = reactive({ color: 'red' }) + const value = ref(false) + const root = document.createElement('div') + + const Child = { + setup() { + onMounted(() => { + con...
packages/runtime-dom/__tests__/helpers/useCssVars.spec.ts
0
TypeScript
1
none
16
51
51
true
fix(runtime-dom): before update should also set css vars
11,561
vuejs/vue-next
25,296
TypeScript
linzhe141
event.startsWith(compatModelEventPrefix)) ) ) { if (!propsOptions || !(toHandlerKey(camelize(event)) in propsOptions)) { warn( `Component emitted event "${event}" but it is neither declared in ` + `the emits option nor as an "${toHandlerKey(camelize(...
No issues found.
event.startsWith(compatModelEventPrefix)) ) ) { if (!propsOptions || !(toHandlerKey(camelize(event)) in propsOptions)) { warn( `Component emitted event "${event}" but it is neither declared in ` + `the emits option nor as an "${toHandlerKey(camelize(...
@@ -228,12 +228,14 @@ export function emit( } } +const mixinEmitsCache = new WeakMap<ConcreteComponent, ObjectEmitsOptions>() export function normalizeEmitsOptions( comp: ConcreteComponent, appContext: AppContext, asMixin = false, ): ObjectEmitsOptions | null { - const cache = appContext.emitsCache + ...
packages/runtime-core/src/componentEmits.ts
0
TypeScript
1
none
16
51
51
true
fix(runtime-core): use separate emits caches for components and mixins
11,661
vuejs/vue-next
25,296
TypeScript
gcaaa31928
const wrapped: any = readonly(original) expect(wrapped.size).toBe(2) for (const [key, value] of wrapped) { expect(isReadonly(key)).toBe(true) expect(isReadonly(value)).toBe(true) } wrapped.forEach((value: any) => { expect(isReadonly(v...
No issues found.
const wrapped: any = readonly(original) expect(wrapped.size).toBe(2) for (const [key, value] of wrapped) { expect(isReadonly(key)).toBe(true) expect(isReadonly(value)).toBe(true) } wrapped.forEach((value: any) => { expect(isReadonly(v...
@@ -496,9 +496,10 @@ describe('reactivity/readonly', () => { const r = ref(false) const ror = readonly(r) const obj = reactive({ ror }) - expect(() => { - obj.ror = true - }).toThrow() + obj.ror = true + expect( + `Set operation on key "ror" failed: target is readonly.`, + ).toHa...
packages/reactivity/__tests__/readonly.spec.ts
0
TypeScript
1
none
16
51
51
true
fix(reactivity): warn on nested readonly ref update during unwrapping
12,141
vuejs/vue-next
25,296
TypeScript
jh-leong
it('can not run an inactive scope', () => { let dummy, doubled const counter = reactive({ num: 0 }) const scope = effectScope() scope.run(() => { effect(() => (dummy = counter.num)) }) expect(scope.effects.length).toBe(1) scope.stop() scope.run(() => { effect(() => (do...
No issues found.
it('can not run an inactive scope', () => { let dummy, doubled const counter = reactive({ num: 0 }) const scope = effectScope() scope.run(() => { effect(() => (dummy = counter.num)) }) expect(scope.effects.length).toBe(1) scope.stop() scope.run(() => { effect(() => (do...
@@ -176,7 +176,7 @@ describe('reactivity/effect/scope', () => { expect('[Vue warn] cannot run an inactive effect scope.').toHaveBeenWarned() - expect(scope.effects.length).toBe(1) + expect(scope.effects.length).toBe(0) counter.num = 7 expect(dummy).toBe(0) @@ -358,5 +358,8 @@ describe('reacti...
packages/reactivity/__tests__/effectScope.spec.ts
0
TypeScript
1
none
16
51
51
true
fix(reactivity): ensure watch cleanup on effect scope stop
12,373
vuejs/vue-next
25,296
TypeScript
edison1105
...genIdentifier( source, context, { start: advancePositionWithClone(node.loc.start, source, start), end: advancePositionWithClone(node.loc.start, source, end), source, }, hasMemberExpression ? undefined : as...
No issues found.
...genIdentifier( source, context, { start: advancePositionWithClone(node.loc.start, source, start), end: advancePositionWithClone(node.loc.start, source, end), source, }, hasMemberExpression ? undefined : as...
@@ -1,4 +1,4 @@ -import { isGloballyAllowed } from '@vue/shared' +import { genPropsAccessExp, isGloballyAllowed } from '@vue/shared' import { BindingTypes, NewlineType, @@ -164,6 +164,12 @@ function genIdentifier( ? `${helper('isRef')}(${raw}) ? (${raw}.value = ${assignment}) : null` ...
packages/compiler-vapor/src/generators/expression.ts
0
TypeScript
1
none
16
51
51
true
fix(defineProps): register type bindings before compile template + props destructure work with vapor
12,545
vuejs/vue-next
25,296
TypeScript
edison1105
import { EMPTY_OBJ, hasOwn, isArray } from '@vue/shared' import { resolveSource } from './componentProps' /** * The logic from core isn't too reusable so it's better to duplicate here */ export function normalizeEmitsOptions( comp: VaporComponent, ): ObjectEmitsOptions | null { const cached = comp.__emitsOptions...
No issues found.
import { EMPTY_OBJ, hasOwn, isArray } from '@vue/shared' import { resolveSource } from './componentProps' /** * The logic from core isn't too reusable so it's better to duplicate here */ export function normalizeEmitsOptions( comp: VaporComponent, ): ObjectEmitsOptions | null { const cached = comp.__emitsOptions...
@@ -18,7 +18,7 @@ export function normalizeEmitsOptions( let normalized: ObjectEmitsOptions if (isArray(raw)) { normalized = {} - for (const key in raw) normalized[key] = null + for (const key of raw) normalized[key] = null } else { normalized = raw }
packages/runtime-vapor/src/componentEmits.ts
0
TypeScript
1
none
16
51
51
true
fix(runtime-vapor): properly normalize emits options if emits is an array
12,614
vuejs/vue-next
25,296
TypeScript
edison1105
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') ...
No issues found.
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') ...
@@ -471,5 +471,30 @@ describe('reactivity/collections', () => { const result = map.set('a', 'a') expect(result).toBe(map) }) + + it('should wrapped iterator inherit all iterator properties', () => { + const raw = new Map([['key', 'value']]) + const map = reactive(raw) + + const rawI...
packages/reactivity/__tests__/collections/Map.spec.ts
0
TypeScript
1
none
16
51
51
true
fix(reactivity): collection iteration should inherit iterator instance methods
12,644
vuejs/vue-next
25,296
TypeScript
edison1105
ComputedGetter, ComputedSetter, ReactiveEffectRunner, ReactiveEffectOptions, EffectScheduler, DebuggerOptions, DebuggerEvent, DebuggerEventExtraInfo, Raw, Reactive, } from '@vue/reactivity' export type { MultiWatchSources, WatchEffect, WatchOptions, WatchEffectOptions as WatchOptionsBase, ...
No issues found.
ComputedGetter, ComputedSetter, ReactiveEffectRunner, ReactiveEffectOptions, EffectScheduler, DebuggerOptions, DebuggerEvent, DebuggerEventExtraInfo, Raw, Reactive, } from '@vue/reactivity' export type { MultiWatchSources, WatchEffect, WatchOptions, WatchEffectOptions as WatchOptionsBase, ...
@@ -64,7 +64,7 @@ export { defineComponent } from './apiDefineComponent' export { defineAsyncComponent } from './apiAsyncComponent' export { useAttrs, useSlots } from './apiSetupHelpers' export { useModel } from './helpers/useModel' -export { useTemplateRef } from './helpers/useTemplateRef' +export { useTemplateRef,...
packages/runtime-core/src/index.ts
0
TypeScript
1
none
16
51
51
true
feat(types): add type TemplateRef
12,645
vuejs/vue-next
25,296
TypeScript
Shinigami92
try { if (__DEV__) { // subs are notified and batched in reverse-order and then invoked in // original order at the end of the batch, but onTrigger hooks should // be invoked in original order here. for (let head = this.subsHead; head; head = head.nextSub) { if (head....
No issues found.
try { if (__DEV__) { // subs are notified and batched in reverse-order and then invoked in // original order at the end of the batch, but onTrigger hooks should // be invoked in original order here. for (let head = this.subsHead; head; head = head.nextSub) { if (head....
@@ -93,6 +93,12 @@ export class Dep { */ sc: number = 0 + /** + * @internal + */ + readonly __v_skip = true + // TODO isolatedDeclarations ReactiveFlags.SKIP + constructor(public computed?: ComputedRefImpl | undefined) { if (__DEV__) { this.subsHead = undefined
packages/reactivity/src/dep.ts
0
TypeScript
1
none
16
51
51
true
fix(reactivity): add `__v_skip` flag to `Dep` to prevent reactive conversion
12,804
vuejs/vue-next
25,296
TypeScript
serkodev
isStatic: true, }, values: [ { content: `fooBar`, isStatic: false, }, ], runtimeCamelize: false, modifier: '.', }, }) expect(code).contains('renderEffect') expect(code).contains('_setDOMProp(n0, "fooBar", _ct...
No issues found.
isStatic: true, }, values: [ { content: `fooBar`, isStatic: false, }, ], runtimeCamelize: false, modifier: '.', }, }) expect(code).contains('renderEffect') expect(code).contains('_setDOMProp(n0, "fooBar", _ct...
@@ -785,6 +785,23 @@ describe('cache multiple access', () => { expect(code).contains('_setProp(n0, "id", _obj[1][_ctx.baz] + _obj.bar)') }) + test('cache variable used in both property shorthand and normal binding', () => { + const { code } = compileWithVBind(` + <div :style="{color}" :id="color"/>...
packages/compiler-vapor/__tests__/transforms/vBind.spec.ts
0
TypeScript
1
none
16
51
51
true
fix(compiler-vapor): properly cache variable used in object property shorthand
12,815
vuejs/vue-next
25,296
TypeScript
edison1105
bar?: number; baz: boolean; qux?(): number; quux?(): void quuxx?: Promise<string>; quuux?: number; fred?: string }>(), { foo: 'hi', qux() { return 1 }, ['quux']() { }, async quuxx() { return await Promise.resolve('hi') }, quuux(a, [b, ...c], {d...
No issues found.
bar?: number; baz: boolean; qux?(): number; quux?(): void quuxx?: Promise<string>; quuux?: number; fred?: string }>(), { foo: 'hi', qux() { return 1 }, ['quux']() { }, async quuxx() { return await Promise.resolve('hi') }, quuux(a, [b, ...c], {d...
@@ -387,12 +387,14 @@ const props = defineProps({ foo: String }) qux?(): number; quux?(): void quuxx?: Promise<string>; + quuux?: number; fred?: string }>(), { foo: 'hi', qux() { return 1 }, ['quux']() { }, async quuxx() { return await Promise.resolve('h...
packages/compiler-sfc/__tests__/compileScript/defineProps.spec.ts
0
TypeScript
1
none
16
51
51
true
fix(compiler-sfc): no params were generated when using withDefaults
12,823
vuejs/vue-next
25,296
TypeScript
inottn
this._ob = null } // unmount this._app && this._app.unmount() if (this._instance) this._instance.ce = undefined this._app = this._instance = null } }) } /** * resolve inner component definition (handle possible async component) */ private _resolve...
No issues found.
this._ob = null } // unmount this._app && this._app.unmount() if (this._instance) this._instance.ce = undefined this._app = this._instance = null } }) } /** * resolve inner component definition (handle possible async component) */ private _resolve...
@@ -280,7 +280,8 @@ export class VueElement // avoid resolving component if it's not connected if (!this.isConnected) return - if (!this.shadowRoot) { + // avoid re-parsing slots if already resolved + if (!this.shadowRoot && !this._resolved) { this._parseSlots() } this._connected =...
packages/runtime-dom/src/apiCustomElement.ts
0
TypeScript
1
none
16
51
51
true
fix(custom-element): ensure proper remount and prevent redundant slot parsing with shadowRoot false
13,201
vuejs/vue-next
25,296
TypeScript
edison1105
} pushTemplate(content: string): number { const existing = this.ir.template.findIndex( template => template === content, ) if (existing !== -1) return existing this.ir.template.push(content) return this.ir.template.length - 1 } registerTemplate(): number { if (!this.template) retu...
No issues found.
} pushTemplate(content: string): number { const existing = this.ir.template.findIndex( template => template === content, ) if (existing !== -1) return existing this.ir.template.push(content) return this.ir.template.length - 1 } registerTemplate(): number { if (!this.template) retu...
@@ -140,8 +140,10 @@ export class TransformContext<T extends AllNode = AllNode> { registerEffect( expressions: SimpleExpressionNode[], - ...operations: OperationNode[] + operation: OperationNode | OperationNode[], + getIndex = (): number => this.block.effect.length, ): void { + const operations...
packages/compiler-vapor/src/transform.ts
0
TypeScript
1
none
16
51
51
true
fix(compiler-vapor): correct execution order of operations
13,351
vuejs/vue-next
25,296
TypeScript
zhiyuanzmj
/* v8 ignore stop */ context.parent!.children[context.childIndex] = context.currentNode = node }, removeNode(node) { /* v8 ignore next 3 */ if (__DEV__ && !context.parent) { throw new Error(`Cannot remove root node.`) } const list = context.parent!.children cons...
No issues found.
/* v8 ignore stop */ context.parent!.children[context.childIndex] = context.currentNode = node }, removeNode(node) { /* v8 ignore next 3 */ if (__DEV__ && !context.parent) { throw new Error(`Cannot remove root node.`) } const list = context.parent!.children cons...
@@ -123,6 +123,11 @@ export interface TransformContext filters?: Set<string> } +export function getSelfName(filename: string): string | null { + const nameMatch = filename.replace(/\?.*$/, '').match(/([^/\\]+)\.\w+$/) + return nameMatch ? capitalize(camelize(nameMatch[1])) : null +} + export function createTra...
packages/compiler-core/src/transform.ts
0
TypeScript
1
none
16
51
51
true
fix(compiler-vapor): resolve implicitly self-referencing component
13,400
vuejs/vue-next
25,296
TypeScript
edison1105
configurable: true, enumerable: true, get: () => getAttr(target.rawProps, key), } } }, } satisfies ProxyHandler<VaporComponentInstance> if (__DEV__) { Object.assign(attrsHandlers, { set: propsSetDevTrap, deleteProperty: propsDeleteDevTrap, }) } ...
No issues found.
configurable: true, enumerable: true, get: () => getAttr(target.rawProps, key), } } }, } satisfies ProxyHandler<VaporComponentInstance> if (__DEV__) { Object.assign(attrsHandlers, { set: propsSetDevTrap, deleteProperty: propsDeleteDevTrap, }) } ...
@@ -186,7 +186,7 @@ export function getAttrFromRawProps(rawProps: RawProps, key: string): unknown { source = dynamicSources[i] isDynamic = isFunction(source) source = isDynamic ? (source as Function)() : source - if (hasOwn(source, key)) { + if (source && hasOwn(source, key)) { c...
packages/runtime-vapor/src/componentProps.ts
0
TypeScript
1
none
16
51
51
true
fix(runtime-vapor): prevent hasOwnProperty error when props is null
13,564
vuejs/vue-next
25,296
TypeScript
zhiyuanzmj
directiveTransforms: { bind: transformVBind }, }) describe('compiler: expression', () => { test('basic', () => { const { code } = compileWithExpression(`{{ a }}`) expect(code).toMatchSnapshot() expect(code).contains(`ctx.a`) }) test('props', () => { const { code } = compileWithExpression(`{{ f...
No issues found.
directiveTransforms: { bind: transformVBind }, }) describe('compiler: expression', () => { test('basic', () => { const { code } = compileWithExpression(`{{ a }}`) expect(code).toMatchSnapshot() expect(code).contains(`ctx.a`) }) test('props', () => { const { code } = compileWithExpression(`{{ f...
@@ -47,4 +47,25 @@ describe('compiler: expression', () => { expect(code).toMatchSnapshot() expect(code).contains(`_String(_foo.id++)`) }) + + test('empty interpolation', () => { + const { code } = compileWithExpression(`{{}}`) + const { code: code2 } = compileWithExpression(`{{ }}`) + const { cod...
packages/compiler-vapor/__tests__/transforms/expression.spec.ts
0
TypeScript
1
none
16
51
51
true
fix(compiler-vapor): handle empty interpolation
13,592
vuejs/vue-next
25,296
TypeScript
LittleSound
// force reflow to put everything in position forceReflow(instance.vnode.el as Node) movedChildren.forEach(c => { const el = c.el as ElementWithTransition const style = el.style addTransitionClass(el, moveClass) style.transform = style.webkitTransform = style.transiti...
No issues found.
// force reflow to put everything in position forceReflow(instance.vnode.el as Node) movedChildren.forEach(c => { const el = c.el as ElementWithTransition const style = el.style addTransitionClass(el, moveClass) style.transform = style.webkitTransform = style.transiti...
@@ -92,7 +92,7 @@ const TransitionGroupImpl: ComponentOptions = /*@__PURE__*/ decorate({ const movedChildren = prevChildren.filter(applyTranslation) // force reflow to put everything in position - forceReflow() + forceReflow(instance.vnode.el as Node) movedChildren.forEach(c => { ...
packages/runtime-dom/src/components/TransitionGroup.ts
0
TypeScript
1
none
16
51
51
true
fix(transition-group): run `forceReflow` on the correct document (fix #13849)
13,853
vuejs/vue-next
25,296
TypeScript
zusorio
}) expect( (parentOp as any).render.dynamic.children[0].children[0].operation, ).toMatchObject({ type: IRNodeTypes.FOR, id: 2, source: { content: 'i' }, value: { content: 'j' }, render: { type: IRNodeTypes.BLOCK, dynamic: { children: [{ template:...
No issues found.
}) expect( (parentOp as any).render.dynamic.children[0].children[0].operation, ).toMatchObject({ type: IRNodeTypes.FOR, id: 2, source: { content: 'i' }, value: { content: 'j' }, render: { type: IRNodeTypes.BLOCK, dynamic: { children: [{ template:...
@@ -368,4 +368,24 @@ describe('compiler: v-for', () => { index: undefined, }) }) + + test('v-for on component', () => { + const { code, ir } = compileWithVFor( + `<Comp v-for="item in list">{{item}}</Comp>`, + ) + expect(code).matchSnapshot() + expect( + (ir.block.dynamic.children[...
packages/compiler-vapor/__tests__/transforms/vFor.spec.ts
0
TypeScript
1
none
16
51
51
true
fix(compiler-vapor): treat template v-for with single component child as component
13,914
vuejs/vue-next
25,296
TypeScript
edison1105
checkDuplicateProperties!(OptionTypes.DATA, key) // expose data on ctx during dev if (!isReservedPrefix(key[0])) { Object.defineProperty(ctx, key, { configurable: true, enumerable: true, get: () => data[key], set: NOOP, ...
No issues found.
checkDuplicateProperties!(OptionTypes.DATA, key) // expose data on ctx during dev if (!isReservedPrefix(key[0])) { Object.defineProperty(ctx, key, { configurable: true, enumerable: true, get: () => data[key], set: NOOP, ...
@@ -852,7 +852,7 @@ export function createWatcher( ): void { let getter = key.includes('.') ? createPathGetter(publicThis, key) - : () => (publicThis as any)[key] + : () => publicThis[key as keyof typeof publicThis] const options: WatchOptions = {} if (__COMPAT__) {
packages/runtime-core/src/componentOptions.ts
0
TypeScript
1
none
16
51
51
true
chore(types): improve type safety in watch functions and instanceWatch
13,918
vuejs/vue-next
25,296
TypeScript
ArthurDarkstone
expect(node.content).toMatchObject({ type: NodeTypes.COMPOUND_EXPRESSION, children: [ { content: `_ctx.foo` }, `.`, { content: `bar` }, `.`, { content: `baz` }, ], }) }) test('should prefix computed id in a member expression', () => { const node...
No issues found.
expect(node.content).toMatchObject({ type: NodeTypes.COMPOUND_EXPRESSION, children: [ { content: `_ctx.foo` }, `.`, { content: `bar` }, `.`, { content: `baz` }, ], }) }) test('should prefix computed id in a member expression', () => { const node...
@@ -716,4 +716,42 @@ describe('compiler: expression transform', () => { }) }) }) + + describe('switch case variable declarations', () => { + test('should handle const declarations in switch case without braces', () => { + const { code } = compile( + `{{ (() => { switch (1) { case 1: const...
packages/compiler-core/__tests__/transforms/transformExpressions.spec.ts
0
TypeScript
1
none
16
51
51
true
fix(compiler-core): identifiers in switch-case should not be inferred as references
13,923
vuejs/vue-next
25,296
TypeScript
wngtk
const { component: Child } = define({ props: ['count'], setup(props: any) { watch( () => props.count, () => { calls.push('child watcher') globalCount.value = props.count }, ) onUpdated(() => calls.push('update child')) ...
No issues found.
const { component: Child } = define({ props: ['count'], setup(props: any) { watch( () => props.count, () => { calls.push('child watcher') globalCount.value = props.count }, ) onUpdated(() => calls.push('update child')) ...
@@ -416,6 +416,22 @@ describe('component', () => { 'Vapor component setup() returned non-block value, and has no render function', ).toHaveBeenWarned() }) + + it('warn non-existent property access', () => { + define({ + setup() { + return {} + }, + render(ctx: any) { + ct...
packages/runtime-vapor/__tests__/component.spec.ts
0
TypeScript
1
none
16
51
51
true
fix(runtime-vapor): add dev-only warning for non-existent property access during render
14,162
vuejs/vue-next
25,296
TypeScript
edison1105
} updateComponentPreRender(instance, n2, optimized) if (__DEV__) { popWarningContext() } return } else { // normal update instance.next = n2 // instance.update is the reactive effect. instance.update() } } else { // ...
No issues found.
} updateComponentPreRender(instance, n2, optimized) if (__DEV__) { popWarningContext() } return } else { // normal update instance.next = n2 // instance.update is the reactive effect. instance.update() } } else { // ...
@@ -1995,8 +1995,8 @@ function baseCreateRenderer( const anchorVNode = c2[nextIndex + 1] as VNode const anchor = nextIndex + 1 < l2 - ? // #13559, fallback to el placeholder for unresolved async component - anchorVNode.el || anchorVNode.placeholder + ? // ...
packages/runtime-core/src/renderer.ts
0
TypeScript
1
none
16
51
51
true
fix(runtime-core): ensure correct anchor el for deeper unresolved async components
14,182
vuejs/vue-next
25,296
TypeScript
linzhe141
DeprecationTypes.COMPONENT_V_MODEL, // this is a special case where we want to use the vnode component's // compat config instead of the current rendering instance (which is the // parent of the component that exposes v-model) { type } as any, ) ) { return } ...
No issues found.
DeprecationTypes.COMPONENT_V_MODEL, // this is a special case where we want to use the vnode component's // compat config instead of the current rendering instance (which is the // parent of the component that exposes v-model) { type } as any, ) ) { return } ...
@@ -1,5 +1,6 @@ import { ShapeFlags, extend } from '@vue/shared' import type { ComponentInternalInstance, ComponentOptions } from '../component' +import { createAppContext } from '../apiCreateApp' import { ErrorCodes, callWithErrorHandling } from '../errorHandling' import type { VNode } from '../vnode' import { po...
packages/runtime-core/src/compat/componentVModel.ts
0
TypeScript
1
none
16
51
51
true
fix(compat): handle v-model deprecation warning with missing appContext
14,203
vuejs/vue-next
25,296
TypeScript
edison1105
}).render() expect(html()).toBe('AAA<!--dynamic-component-->') val.value = B await nextTick() expect(html()).toBe('AAA<!--dynamic-component-->') // still AAA }) test('fallback with v-once', async () => { const val = shallowRef<any>('button') const id = ref(0) const { html } = defi...
No issues found.
}).render() expect(html()).toBe('AAA<!--dynamic-component-->') val.value = B await nextTick() expect(html()).toBe('AAA<!--dynamic-component-->') // still AAA }) test('fallback with v-once', async () => { const val = shallowRef<any>('button') const id = ref(0) const { html } = defi...
@@ -179,4 +179,15 @@ describe('api: createDynamicComponent', () => { '<div><span>hi</span><!--slot--></div><!--dynamic-component-->', ) }) + + test('accept blocks', async () => { + const { html } = define({ + setup() { + const n0 = template('<a>router link</a>')() + return createDy...
packages/runtime-vapor/__tests__/apiCreateDynamicComponent.spec.ts
0
TypeScript
1
none
16
51
51
true
feat(runtime-vapor): support render block in createDynamicComponent
14,213
vuejs/vue-next
25,296
TypeScript
edison1105
el.textContent = vnode.children as string } } // props if (props) { if ( __DEV__ || __FEATURE_PROD_HYDRATION_MISMATCH_DETAILS__ || forcePatch || !optimized || patchFlag & (PatchFlags.FULL_PROPS | PatchFlags.NEED_HYDRATION) ...
No issues found.
el.textContent = vnode.children as string } } // props if (props) { if ( __DEV__ || __FEATURE_PROD_HYDRATION_MISMATCH_DETAILS__ || forcePatch || !optimized || patchFlag & (PatchFlags.FULL_PROPS | PatchFlags.NEED_HYDRATION) ...
@@ -507,7 +507,7 @@ export function createHydrationFunctions( (isOn(key) && !isReservedProp(key)) || // force hydrate v-bind with .prop modifiers key[0] === '.' || - isCustomElement + (isCustomElement && !isReservedProp(key)) ) { ...
packages/runtime-core/src/hydration.ts
0
TypeScript
1
none
16
51
51
true
fix(runtime-core): skip patching reserved props for custom elements
14,275
vuejs/vue-next
25,296
TypeScript
danielroe
postClone, ) if (postClone) postClone(hooks) return hooks }, } return context } export function resolveTransitionHooks( block: TransitionBlock, props: TransitionProps, state: TransitionState, instance: GenericComponentInstance, postClone?: (hooks: TransitionHooks) => void, )...
No issues found.
postClone, ) if (postClone) postClone(hooks) return hooks }, } return context } export function resolveTransitionHooks( block: TransitionBlock, props: TransitionProps, state: TransitionState, instance: GenericComponentInstance, postClone?: (hooks: TransitionHooks) => void, )...
@@ -88,7 +88,10 @@ const decorate = (t: typeof VaporTransition) => { } export const VaporTransition: FunctionalVaporComponent<TransitionProps> = - /*@__PURE__*/ decorate((props, { slots }) => { + /*@__PURE__*/ decorate((props, { slots, expose }) => { + // @ts-expect-error + expose() + // Register trans...
packages/runtime-vapor/src/components/Transition.ts
0
TypeScript
1
none
16
51
51
true
fix(runtime-vapor): avoid exposing built-in components internals via template ref
14,448
vuejs/vue-next
25,296
TypeScript
edison1105
"django-treebeard>=4.2.0,<5.0", "djangorestframework>=3.7.4,<4.0", "django-filter>=2.2,<3.0", "draftjs_exporter>=2.1.5,<3.0", "Pillow>=4.0.0,<8.0.0", "beautifulsoup4>=4.8,<4.9", "html5lib>=0.999,<2", "Unidecode>=0.04.14,<2.0", "Willow>=1.3,<1.4", "requests>=2.11.1,<3.0", "l18...
Could you add version checks here?
"djangorestframework>=3.11.1,<4.0", "django-filter>=2.2,<22", "draftjs_exporter>=2.1.5,<3.0", "Pillow>=4.0.0,<9.0.0", "beautifulsoup4>=4.8,<4.10", "html5lib>=0.999,<2", "Willow>=1.4,<1.5", "requests>=2.11.1,<3.0", "l18n>=2018.5", "xlsxwriter>=1.2.8,<4.0", "tablib[xls,xlsx]>=0...
@@ -49,6 +49,8 @@ 'boto3>=1.4,<1.5', 'freezegun>=0.3.8', 'openpyxl>=2.6.4', + 'azure-mgmt-cdn',
setup.py
26
Python
0.143
question
34
51
51
false
Add Azure CDN and Front Door front-end cache invalidation support
6,119
wagtail/wagtail
16,097
Python
kaedroho
tm-kn
try: self.client.create_invalidation( DistributionId=distribution_id, InvalidationBatch={ 'Paths': { 'Quantity': len(paths), 'Items': paths }, 'CallerReference...
We've tightened up the flake8 config recently so it won't allow three spaces here anymore, please could you rebase this on the latest master?
def _create_invalidation(self, distribution_id, paths): import botocore try: self.client.create_invalidation( DistributionId=distribution_id, InvalidationBatch={ 'Paths': { 'Quantity': len(paths), ...
@@ -199,3 +199,169 @@ def _create_invalidation(self, distribution_id, paths): e.response['Error']['Code'], e.response['Error']['Message'] ) + +
wagtail/contrib/frontend_cache/backends.py
26
Python
0.429
question
141
51
51
false
Add Azure CDN and Front Door front-end cache invalidation support
6,119
wagtail/wagtail
16,097
Python
kaedroho
tm-kn
return ''; } let element = fieldNode.closest('[data-contentpath]'); const contentPaths = []; while (element !== null) { contentPaths.push(element.dataset.contentpath); element = element.parentElement.closest('[data-contentpath]'); } contentPaths.reverse(); return contentPaths.join('.'); } cla...
**Question:** Building content paths from the DOM structure... Hmm... I am not sure if I like this. Is there a reason for this? This is quite clever, but couldn't we have a function written in Python to do the same thing and just return the absolute paths via a dataset property? Don't like relying on template structure...
}; document.addEventListener('DOMContentLoaded', () => { const commentsElement = document.getElementById('comments'); const author = JSON.parse(document.getElementById('comments-author').textContent); if (commentsElement && author) { window.commentApp = initCommentsApp(commentsElement, author, in...
@@ -0,0 +1,144 @@ +import { initCommentsApp } from 'wagtail-comment-frontend'; +import { STRINGS } from '../../config/wagtailConfig'; + +function initComments(element, author, initialComments) { + const app = initCommentsApp(element, author, initialComments, STRINGS); + window.commentApp = app; + return app; +} + +f...
client/src/components/CommentApp/comments.js
26
JavaScript
0.5
question
417
51
51
false
Feature/field comment frontend
6,530
wagtail/wagtail
16,097
Python
tm-kn
emilytoppm
import { STRINGS } from '../../config/wagtailConfig'; function initComments(element, author, initialComments) { const app = initCommentsApp(element, author, initialComments, STRINGS); window.commentApp = app; return app; } function getContentPath(fieldNode) { // Return the total contentpath for an element as ...
**Question:** Is closest compatible with Internet Explorer? Do we need to have a polyfill?
import { STRINGS } from '../../config/wagtailConfig'; function initComments(initialComments) { // in case any widgets try to initialise themselves before the comment app, // store their initialisations as callbacks to be executed when the comment app // itself is finished initialising. const callbacks = []; ...
@@ -0,0 +1,144 @@ +import { initCommentsApp } from 'wagtail-comment-frontend'; +import { STRINGS } from '../../config/wagtailConfig'; + +function initComments(element, author, initialComments) { + const app = initCommentsApp(element, author, initialComments, STRINGS); + window.commentApp = app; + return app; +} + +f...
client/src/components/CommentApp/comments.js
26
JavaScript
0.214
question
90
51
51
false
Feature/field comment frontend
6,530
wagtail/wagtail
16,097
Python
tm-kn
emilytoppm
// and that screenreader users can return to the annotation point when desired } show() { this.node.classList.remove('u-hidden'); } hide() { this.node.classList.add('u-hidden'); } setOnClickHandler(handler) { this.node.addEventListener('click', handler); } getDesiredPosition() { retu...
**Nitpick (non-blocking):** When we have this many positional arguments, code may be slightly more readable if we use an object so the parameters can be spelt out explicitly when you pass in the arguments.
this.node = node; this.fieldNode = fieldNode; this.position = ''; } onDelete() { this.node.remove(); } onFocus() { this.node.classList.remove('button-secondary'); this.node.ariaLabel = STRINGS.UNFOCUS_COMMENT; } onUnfocus() { this.node.classList.add('button-secondary'); this....
@@ -0,0 +1,144 @@ +import { initCommentsApp } from 'wagtail-comment-frontend'; +import { STRINGS } from '../../config/wagtailConfig'; + +function initComments(element, author, initialComments) { + const app = initCommentsApp(element, author, initialComments, STRINGS); + window.commentApp = app; + return app; +} + +f...
client/src/components/CommentApp/comments.js
26
JavaScript
0.5
nitpick
205
51
51
false
Feature/field comment frontend
6,530
wagtail/wagtail
16,097
Python
tm-kn
emilytoppm
this.commentAdditionNode.insertAdjacentElement('afterend', annotationNode); return new BasicFieldLevelAnnotation(this.fieldNode, annotationNode); } addComment() { this.commentApp.makeComment( this.getAnnotationForComment(), this.contentPath ); } } function initFieldLevelCommentWidget(...
**Question:** Would the JS be loaded before `DOMContentLoaded`? I think the full page load is a separate event. I think this event only refers to the DOM, not the actual JS code. Is this an actual issue or are we just prematurely optimising? And frankly, we're repeating the init. This looks like a code smell.
this.commentAdditionNode.classList.add('u-hidden'); } else { this.commentAdditionNode.classList.remove('u-hidden'); } } getAnnotationForComment() { const annotationNode = this.annotationTemplateNode.cloneNode(true); annotationNode.id = ''; this.commentAdditionNode.insertAdjacentEleme...
@@ -0,0 +1,144 @@ +import { initCommentsApp } from 'wagtail-comment-frontend'; +import { STRINGS } from '../../config/wagtailConfig'; + +function initComments(element, author, initialComments) { + const app = initCommentsApp(element, author, initialComments, STRINGS); + window.commentApp = app; + return app; +} + +f...
client/src/components/CommentApp/comments.js
26
JavaScript
0.571
suggestion
310
38
30
false
Feature/field comment frontend
6,530
wagtail/wagtail
16,097
Python
tm-kn
emilytoppm
# Check that both recommendations were deleted self.assertFalse( SearchPromotion.objects.filter(id=self.search_pick_2.id).exists() ) # The other recommendation should still exist self.assertFalse( SearchPromotion.objects.filter(id=self.search_pick.id).exi...
Nitpick. Same as other comment? `old ; these` -> `old. These`
# Check that both recommendations were deleted self.assertFalse( SearchPromotion.objects.filter(id=self.search_pick_2.id).exists() ) # The other recommendation should still exist self.assertFalse( SearchPromotion.objects.filter(id=self.search_pick.id).exi...
@@ -485,3 +492,92 @@ def test_post(self): self.assertFalse( SearchPromotion.objects.filter(id=self.search_pick.id).exists() ) + + +class TestGarbageCollectManagementCommand(TestCase): + def test_garbage_collect_command(self): + nowdt = datetime.now() + old_hit_date = (now...
wagtail/contrib/search_promotions/tests.py
26
Python
0.357
nitpick
61
51
51
false
Move Query model to search promotions
7,277
wagtail/wagtail
16,097
Python
allcaps
kaedroho
'comments-INITIAL_FORMS': '0', 'comments-MIN_NUM_FORMS': '0', 'comments-MAX_NUM_FORMS': '', 'comments-0-DELETE': '', 'comments-0-resolved': '', 'comments-0-id': '', 'comments-0-contentpath': 'title', 'comments-0-text': 'A te...
I think the linting is flagging this extra line here as an issue.
'comments-INITIAL_FORMS': '0', 'comments-MIN_NUM_FORMS': '0', 'comments-MAX_NUM_FORMS': '', 'comments-0-DELETE': '', 'comments-0-resolved': '', 'comments-0-id': '', 'comments-0-contentpath': 'title', 'comments-0-text': 'A te...
@@ -2564,3 +2564,40 @@ def test_updated_comments_notifications_profile_setting(self): # This time, no emails should be submitted because the only subscriber has disabled these emails globally self.assertEqual(len(mail.outbox), 0) + + def test_updated_comments_notifications_active_users_only(self)...
wagtail/admin/tests/pages/test_edit_page.py
26
Python
0.214
style
65
27
26
false
Notifications to active users only
7,510
wagtail/wagtail
16,097
Python
lb-
bwilliams3
def unpublish_hook(self, pages, action): assert action == "unpublish" assert isinstance(pages, list) def missing_hook_action(self, pages, action): assert action == "" assert isinstance(pages, list) @override_settings(WAGTAILSIMPLETRANSLATION_SYNC_PAGE_TREE=True) def tes...
so.. this is fine, but best to add a note and another assertion ``` defined_hooks = hooks.get_hooks("construct_synced_page_tree_list") for fn in defined_hooks: # We should have two implementations. # One in simple_tranalation.wagtail_hook and the other registered above self.assertEqual(len(defined_...
def unpublish_hook(self, pages, action): self.assertEqual(action, "unpublish") self.assertIsInstance(pages, list) def missing_hook_action(self, pages, action): self.assertEqual(action, "") self.assertIsInstance(pages, list) def test_double_registered_hook(self): # W...
@@ -102,3 +103,71 @@ def test_page_listing_more_buttons(self): list(page_listing_more_buttons(blog_page, page_perms))[0], wagtailadmin_widgets.Button, ) + + +class TestConstructSyncedPageTreeListHook(Utils): + def unpublish_hook(self, pages, action): + assert action == "unpu...
wagtail/contrib/simple_translation/tests/test_wagtail_hooks.py
26
Python
0.857
suggestion
606
51
51
false
construct_synced_page_tree_list hook tests
8,058
wagtail/wagtail
16,097
Python
zerolab
KalobTaulien
import os from django.contrib.messages import constants as message_constants from django.utils.translation import gettext_lazy as _ DEBUG = False WAGTAIL_ROOT = os.path.dirname(os.path.dirname(__file__)) # BASE_URL = "http://testserver" WAGTAILADMIN_BASE_URL = "http://testserver" STATIC_ROOT = os.path.join(WAGTAIL_RO...
we should not need this commented out code
import os from django.contrib.messages import constants as message_constants from django.utils.translation import gettext_lazy as _ DEBUG = False WAGTAIL_ROOT = os.path.dirname(os.path.dirname(__file__)) WAGTAILADMIN_BASE_URL = "http://testserver" STATIC_ROOT = os.path.join(WAGTAIL_ROOT, "tests", "test-static") MEDIA...
@@ -5,7 +5,8 @@ DEBUG = False WAGTAIL_ROOT = os.path.dirname(os.path.dirname(__file__)) -BASE_URL = "http://testserver" +# BASE_URL = "http://testserver"
wagtail/test/settings.py
8
Python
0.143
suggestion
42
33
33
false
Renaming base url setting
8,268
wagtail/wagtail
16,097
Python
lb-
sandilsranasinghe
from django.conf import settings def get_admin_base_url(context=None): """ Gets the base URL for the wagtail admin site. This is set in `settings.WAGTAILADMIN_BASE_URL`, which was previously `settings.BASE_URL`. If setting is omitted and this is called in a request context, falls back to `request....
We may want to add a deprecated warning here, but only if `WAGTAILADMIN_BASE_URL` is `None` and `BASE_URL` is not `None`. See `wagtail/utils/deprecation.py` for the utils we use for this. This would probably be a two release warning, so I recommend you use `RemovedInWagtail50Warning`, you can search through the c...
from warnings import warn from django.conf import settings from wagtail.utils.deprecation import RemovedInWagtail50Warning def get_admin_base_url(context=None): """ Gets the base URL for the wagtail admin site. This is set in `settings.WAGTAILADMIN_BASE_URL`, which was previously `settings.BASE_URL`. ...
@@ -0,0 +1,26 @@ +from django.conf import settings + + +def get_admin_base_url(context=None): + """ + Gets the base URL for the wagtail admin site. This is set in `settings.WAGTAILADMIN_BASE_URL`, + which was previously `settings.BASE_URL`. + If setting is omitted and this is called in a request context, fa...
wagtail/admin/utils.py
14
Python
0.643
suggestion
343
27
35
false
Renaming base url setting
8,268
wagtail/wagtail
16,097
Python
lb-
sandilsranasinghe
}); } window.enableDirtyFormCheck = enableDirtyFormCheck; $(() => { // Add class to the body from which transitions may be hung so they don't appear to transition as the page loads $('body').addClass('ready'); // Enable nice focus effects on all fields. This enables help text on hover. // eslint-disable-ne...
thought: this feels the right type of change to slowly move away from jQuery. Could this be accomplished with vanilla JS? 🤔
}); } window.enableDirtyFormCheck = enableDirtyFormCheck; $(() => { // Add class to the body from which transitions may be hung so they don't appear to transition as the page loads $('body').addClass('ready'); // Enable nice focus effects on all fields. This enables help text on hover. // eslint-disable-ne...
@@ -244,13 +244,18 @@ $(() => { }); /* Functions that need to run/rerun when active tabs are changed */ - document.addEventListener('tab-changed', () => { - // Resize autosize textareas + function resizeTextAreas() {
client/src/entrypoints/admin/core.js
26
JavaScript
0.571
performance
124
51
51
false
Resize textareas onload and tab-changed event
8,442
wagtail/wagtail
16,097
Python
zerolab
stevedya
$(this).closest('.field').addClass('focused'); $(this).closest('fieldset').addClass('focused'); $(this).closest('li').addClass('focused'); }); // eslint-disable-next-line func-names $(document).on('blur mouseout', 'input,textarea,select', function () { $(this).closest('.field').removeClass('focus...
```suggestion $(document).on('wagtail:tab-changed', resizeTextAreas); ```
$(this).closest('.field').addClass('focused'); $(this).closest('fieldset').addClass('focused'); $(this).closest('li').addClass('focused'); }); // eslint-disable-next-line func-names $(document).on('blur mouseout', 'input,textarea,select', function () { $(this).closest('.field').removeClass('focus...
@@ -244,13 +244,18 @@ $(() => { }); /* Functions that need to run/rerun when active tabs are changed */ - document.addEventListener('tab-changed', () => { - // Resize autosize textareas + function resizeTextAreas() { // eslint-disable-next-line func-names $('textarea[data-autosize-on]').each(func...
client/src/entrypoints/admin/core.js
26
JavaScript
0.643
suggestion
77
51
51
false
Resize textareas onload and tab-changed event
8,442
wagtail/wagtail
16,097
Python
thibaudcolas
stevedya
e.preventDefault(); this.selectTab(tab); }); tab.addEventListener('focusin', () => { this.selectTab(tab); }); tab.addEventListener('keydown', this.keydownEventListener); // Set index of tab used in keyboard controls // eslint-disable-next-line no-param-reassig...
```suggestion document.addEventListener('DOMContentLoaded', () => { ``` We should be using `addEventListener` for this rather than the global callback. Technically all of the tabs initialisations are meant to be happening after `DOMContentLoaded` anyway, so I don’t see why we’d even want to dispatch the event ...
e.preventDefault(); this.selectTab(tab); }); tab.addEventListener('focusin', () => { this.selectTab(tab); }); tab.addEventListener('keydown', this.keydownEventListener); // Set index of tab used in keyboard controls // eslint-disable-next-line no-param-reassig...
@@ -230,6 +230,13 @@ class Tabs { } } }); + + // Dispatch tab-changed on window load + window.onload = () => {
client/src/includes/tabs.js
26
JavaScript
0.857
suggestion
335
51
51
false
Resize textareas onload and tab-changed event
8,442
wagtail/wagtail
16,097
Python
thibaudcolas
stevedya
this.selectTab(tab); }); tab.addEventListener('focusin', () => { this.selectTab(tab); }); tab.addEventListener('keydown', this.keydownEventListener); // Set index of tab used in keyboard controls // eslint-disable-next-line no-param-reassign tab.index = index; ...
I don’t see how this could ever not be set? We’re already relying on `this.tabContainer` being defined elsewhere so I don’t see what this protects us from.
this.selectTab(tab); }); tab.addEventListener('focusin', () => { this.selectTab(tab); }); tab.addEventListener('keydown', this.keydownEventListener); // Set index of tab used in keyboard controls // eslint-disable-next-line no-param-reassign tab.index = index; ...
@@ -230,6 +230,13 @@ class Tabs { } } }); + + // Dispatch tab-changed on window load + window.onload = () => { + if (this.tabContainer) {
client/src/includes/tabs.js
26
JavaScript
0.571
suggestion
155
51
51
false
Resize textareas onload and tab-changed event
8,442
wagtail/wagtail
16,097
Python
thibaudcolas
stevedya
}); tab.addEventListener('focusin', () => { this.selectTab(tab); }); tab.addEventListener('keydown', this.keydownEventListener); // Set index of tab used in keyboard controls // eslint-disable-next-line no-param-reassign tab.index = index; }); // Select previou...
Could we dispatch this only one time in `initTabs`, rather than once per set of tabs?
}); tab.addEventListener('focusin', () => { this.selectTab(tab); }); tab.addEventListener('keydown', this.keydownEventListener); // Set index of tab used in keyboard controls // eslint-disable-next-line no-param-reassign tab.index = index; }); // Select previou...
@@ -230,6 +230,13 @@ class Tabs { } } }); + + // Dispatch tab-changed on window load + window.onload = () => { + if (this.tabContainer) { + document.dispatchEvent(new CustomEvent('wagtail:tab-changed'));
client/src/includes/tabs.js
26
JavaScript
0.429
question
85
51
51
false
Resize textareas onload and tab-changed event
8,442
wagtail/wagtail
16,097
Python
thibaudcolas
stevedya
max_length=255, verbose_name=_("object id"), ) submitted_for_moderation = models.BooleanField( verbose_name=_("submitted for moderation"), default=False, db_index=True ) created_at = models.DateTimeField(db_index=True, verbose_name=_("created at")) user = models.ForeignKey( ...
This means that the `content_object` is always an instance of the specific page type. I don't think there's a downside to this as all tests seem to pass (after some minor adjustments in this PR) and we even considered enforcing that `save_revision()` is called with a specific page object (#8573).
) submitted_for_moderation = models.BooleanField( verbose_name=_("submitted for moderation"), default=False, db_index=True ) created_at = models.DateTimeField(db_index=True, verbose_name=_("created at")) user = models.ForeignKey( settings.AUTH_USER_MODEL, verbose_name=_("user...
@@ -2238,15 +2235,9 @@ class Revision(models.Model): page_revisions = PageRevisionsManager() submitted_revisions = SubmittedRevisionsManager() - @cached_property - def content_object(self): - return self.base_content_type.get_object_for_this_type(pk=self.object_id) - - @cached_property - ...
wagtail/models/__init__.py
26
Python
0.786
suggestion
297
51
51
false
Use `GenericForeignKey` and `GenericRelation` for `Revision`
8,571
wagtail/wagtail
16,097
Python
laymonage
laymonage
attrs.update(extra_attributes) return mark_safe(f"<img{flatatt(attrs)}>") def __html__(self): return self.img_tag() def get_upload_to(self, filename): """ Generates a file path within the "images" folder by combining the folder name and the validated filename. ...
```suggestion # We only include fields to check if they are a UniqueConstraint, and # they have no condition on them. ```
attrs.update(extra_attributes) return mark_safe(f"<img{flatatt(attrs)}>") def __html__(self): return self.img_tag() def get_upload_to(self, filename): """ Generates a file path within the "images" folder by combining the folder name and the validated filename. ...
@@ -1384,16 +1384,35 @@ def get_upload_to(self, filename): def check(cls, **kwargs): errors = super().check(**kwargs) if not cls._meta.abstract: - if not any( + in_unique_together = any( set(constraint) == {"image", "filter_spec", "focal_point_key"} ...
wagtail/images/models.py
26
Python
0.714
suggestion
148
51
51
false
Adds support for constraints on AbstractRendition, as an alternative to unique_together
8,716
wagtail/wagtail
16,097
Python
Stormheg
ollz272
set(constraint) == {"image", "filter_spec", "focal_point_key"} for constraint in cls._meta.unique_together ) # We only include fields to check if they are a UniqueConstraint, a # nd they have no condition on them. unique_constraint_fields ...
**Suggestion:** should we change this to _only_ refer to UniqueConstraint? This pushes people towards the way [the way Django recommends you define constraints](https://docs.djangoproject.com/en/5.1/ref/models/options/#unique-together).
# a `UniqueConstraint` in `constraints`. unique_constraint_fields = {"image", "filter_spec", "focal_point_key"} in_unique_together = any( set(constraint) == unique_constraint_fields for constraint in cls._meta.unique_together ) ...
@@ -1384,16 +1384,35 @@ def get_upload_to(self, filename): def check(cls, **kwargs): errors = super().check(**kwargs) if not cls._meta.abstract: - if not any( + in_unique_together = any( set(constraint) == {"image", "filter_spec", "focal_point_key"} ...
wagtail/images/models.py
26
Python
0.5
suggestion
236
51
51
false
Adds support for constraints on AbstractRendition, as an alternative to unique_together
8,716
wagtail/wagtail
16,097
Python
Stormheg
ollz272
def get_upload_to(self, filename): """ Generates a file path within the "images" folder by combining the folder name and the validated filename. """ folder_name = "images" filename = self.file.field.storage.get_valid_name(filename) return os.path.join(folder_name, fi...
I think this can be simplified as a single-pass loop like the following: ```suggestion in_unique_constraint = any( isinstance(constraint, models.UniqueConstraint) and constraint.condition is None and set(constraint.fields) == {"image", "filter_spec", "focal_point_key"}...
def get_upload_to(self, filename): """ Generates a file path within the "images" folder by combining the folder name and the validated filename. """ folder_name = "images" filename = self.file.field.storage.get_valid_name(filename) return os.path.join(folder_name, fi...
@@ -1384,16 +1384,35 @@ def get_upload_to(self, filename): def check(cls, **kwargs): errors = super().check(**kwargs) if not cls._meta.abstract: - if not any( + in_unique_together = any( set(constraint) == {"image", "filter_spec", "focal_point_key"} ...
wagtail/images/models.py
26
Python
0.786
suggestion
389
51
51
false
Adds support for constraints on AbstractRendition, as an alternative to unique_together
8,716
wagtail/wagtail
16,097
Python
laymonage
ollz272
""" Generates a file path within the "images" folder by combining the folder name and the validated filename. """ folder_name = "images" filename = self.file.field.storage.get_valid_name(filename) return os.path.join(folder_name, filename) @classmethod def check(...
I considered adding another check to warn when both `unique_together` and `UniqueConstraint` is used (like we did for `TranslatableMixin`). However, I think this is unlikely to happen because unlike `TranslatableMixin`, we don't put a default `unique_together` in `AbstractRendition`, so the option is completely up to t...
""" Generates a file path within the "images" folder by combining the folder name and the validated filename. """ folder_name = "images" filename = self.file.field.storage.get_valid_name(filename) return os.path.join(folder_name, filename) @classmethod def check(...
@@ -1384,16 +1384,35 @@ def get_upload_to(self, filename): def check(cls, **kwargs): errors = super().check(**kwargs) if not cls._meta.abstract: - if not any( + in_unique_together = any( set(constraint) == {"image", "filter_spec", "focal_point_key"} ...
wagtail/images/models.py
26
Python
0.643
refactor
334
51
51
false
Adds support for constraints on AbstractRendition, as an alternative to unique_together
8,716
wagtail/wagtail
16,097
Python
laymonage
ollz272
img.__html__(), f"<picture>{self.rendition_10.img_tag()}</picture>" ) @override_settings( CACHES={"default": {"BACKEND": "django.core.cache.backends.dummy.DummyCache"}} ) class TestRenditions(TestCase): SPECS = ("height-66", "width-100", "width-400") def setUp(self): # Create ...
Unfortunately these only test the "happy path" where either `unique_together` or `CustomRendition` is defined, but not when none of them are defined and the warning is triggered. I think we can follow the approach in #11112 where we dynamically modify the model's `._meta`, call `.check()`, and revert the modifications.
self.assertHTMLEqual( img.__html__(), f"<picture>{self.rendition_10.img_tag()}</picture>" ) @override_settings( CACHES={"default": {"BACKEND": "django.core.cache.backends.dummy.DummyCache"}} ) class TestRenditions(TestCase): SPECS = ("height-66", "width-100", "width-400") def ...
@@ -520,6 +521,12 @@ def setUp(self): def test_get_rendition_model(self): self.assertIs(Image.get_rendition_model(), Rendition) + def test_stock_rendition_contains_unique_together_constraint(self): + self.assertEqual([], Rendition.check()) + + def test_custom_rendition_may_have_unique_const...
wagtail/images/tests/test_models.py
26
Python
0.571
suggestion
320
51
51
false
Adds support for constraints on AbstractRendition, as an alternative to unique_together
8,716
wagtail/wagtail
16,097
Python
laymonage
ollz272
) # We only include fields to check if they are a UniqueConstraint, and # they have no conditions on them. unique_constraint_fields = [ constraint.fields for constraint in cls._meta.constraints if ( isin...
I think this should be the new error message itself (right now the error message still uses `unique_together`), and the `hint` should be something the developer can use, e.g. suggesting ```py "Add models.UniqueConstraint(fields={'image', 'filter_spec', 'focal_point_key'}, " ...
in_unique_together = any( set(constraint) == unique_constraint_fields for constraint in cls._meta.unique_together ) in_unique_constraint = any( isinstance(constraint, models.UniqueConstraint) and constraint.condition is ...
@@ -1384,16 +1384,35 @@ def get_upload_to(self, filename): def check(cls, **kwargs): errors = super().check(**kwargs) if not cls._meta.abstract: - if not any( + in_unique_together = any( set(constraint) == {"image", "filter_spec", "focal_point_key"} ...
wagtail/images/models.py
26
Python
1
suggestion
426
51
51
false
Adds support for constraints on AbstractRendition, as an alternative to unique_together
8,716
wagtail/wagtail
16,097
Python
laymonage
ollz272
# Login self.login(username="test2", password="password") def test_delete_permitted(self): response = self.client.get("/admin/tests/eventpage/delete/4/") self.assertRedirects(response, "/admin/") class TestModeratorAccess(TestCase, WagtailTestUtils): fixtures = ["test_specific...
Please add a new test in both test files that the back link exists and goes to the right location.
business_editors.permissions.add( Permission.objects.get(codename="access_admin") ) GroupPagePermission.objects.create( group=business_editors, page=business_index, permission_type="add" ) GroupPagePermission.objects.create( group=business_edit...
@@ -336,81 +336,6 @@ def test_delete_permitted(self): ) -class TestHeaderBreadcrumbs(TestCase, WagtailTestUtils):
wagtail/contrib/modeladmin/tests/test_page_modeladmin.py
26
Python
0.214
suggestion
98
39
51
false
Remove breadcrumbs from ModelAdmin
8,743
wagtail/wagtail
16,097
Python
lb-
PaarthAgarwal
""" Wrapper for Django's static file finder to append a cache-busting query parameter that updates on each Wagtail version """ return versioned_static_func(path) @register.inclusion_tag("wagtailadmin/shared/icon.html", takes_context=False) def icon(name=None, class_name="icon", title=None, wrapped...
suggestion: add a deprecation warning so we can fully remove this in 2 releases?
""" Wrapper for Django's static file finder to append a cache-busting query parameter that updates on each Wagtail version """ return versioned_static_func(path) @register.inclusion_tag("wagtailadmin/shared/icon.html", takes_context=False) def icon(name=None, classname=None, title=None, wrapped=Fa...
@@ -669,24 +669,30 @@ def versioned_static(path): @register.inclusion_tag("wagtailadmin/shared/icon.html", takes_context=False) -def icon(name=None, class_name="icon", title=None, wrapped=False): +def icon(name=None, classname=None, title=None, wrapped=False, class_name=None): """ Abstracts away the actu...
wagtail/admin/templatetags/wagtailadmin_tags.py
26
Python
0.286
refactor
80
51
51
false
Ensure icon template tag can use `classname` instead of `class_name` by default
9,769
wagtail/wagtail
16,097
Python
zerolab
lb-
}); it('should throw an error if the fetch fails', () => { const application = Application.start(); application.register('w-upgrade', UpgradeController); // Spy on console.error to verify that it is called with the expected error message jest.spyOn(console, 'error').mockImplementation(() => {}); ...
You can probably just disable the Eslint no console directive for this whole file.
application = Application.start(); application.register('w-upgrade', UpgradeController); // trigger next browser render cycle await Promise.resolve(true); expect( document.getElementById('panel').classList.contains('w-hidden'), ).toBe(true); }); it('should throw an error if the fetc...
@@ -0,0 +1,133 @@ +import { Application } from '@hotwired/stimulus'; + +import { UpgradeController } from './UpgradeController'; + +// https://stackoverflow.com/a/51045733 +const flushPromises = () => new Promise(setImmediate); + +describe('UpgradeController', () => { + const url = 'https://releases.wagtail.org/mock.t...
client/src/controllers/UpgradeController.test.js
26
JavaScript
0.214
suggestion
83
31
41
false
Upgrade notification stimulus
9,801
wagtail/wagtail
16,097
Python
lb-
Lovelyfin00
currentVersion: String, ltsOnly: { default: false, type: Boolean }, url: { default: 'https://releases.wagtail.org/latest.txt', type: String }, }; currentVersionValue: string; hiddenClass: string; ltsOnlyValue: any; latestVersionTarget: HTMLElement; linkTarget: HTMLElement; urlValue: string; ...
We could probably use Stimulus' error callbacks here - avoids us calling console.error directly Double check but I'm pretty sure you can just throw an error and Stimulus will just handle this Async and push it to logging if needed. It won't break the whole JS UI - just stop the specific controller method from being...
* * Expected JSON payload: * * { * "version": "2.15.2", * "url": "https://docs.wagtail.io/en/stable/releases/2.15.2.html", * "minorUrl": "https://docs.wagtail.io/en/stable/releases/2.15.html", * "lts": { * "version": "2.12.8", * "url": "https://docs.wagtail.io/en/stable/rel...
@@ -0,0 +1,84 @@ +import { Controller } from '@hotwired/stimulus'; +import { VersionNumber, VersionDeltaType } from '../utils/version'; + +export class UpgradeController extends Controller<HTMLElement> { + static classes = ['hidden']; + static targets = ['latestVersion', 'link']; + static values = { + currentVers...
client/src/controllers/UpgradeController.ts
26
TypeScript
1
suggestion
524
51
51
false
Upgrade notification stimulus
9,801
wagtail/wagtail
16,097
Python
lb-
Lovelyfin00
if (data && data.version) { const latestVersion = new VersionNumber(data.version); const versionDelta = currentVersion.howMuchBehind(latestVersion); let releaseNotesUrl = null; if (!versionDelta) { return; } if ( versionDelta ...
It might be good to pull out this block (that writes the version) to a seperate method. But not critical
fetch(releasesUrl, { referrerPolicy: 'strict-origin-when-cross-origin', }) .then((response) => { if (response.status !== 200) { throw Error( `Unexpected response from ${releasesUrl}. Status: ${response.status}`, ); } return response.json(); ...
@@ -0,0 +1,84 @@ +import { Controller } from '@hotwired/stimulus'; +import { VersionNumber, VersionDeltaType } from '../utils/version'; + +export class UpgradeController extends Controller<HTMLElement> { + static classes = ['hidden']; + static targets = ['latestVersion', 'link']; + static values = { + currentVers...
client/src/controllers/UpgradeController.ts
26
TypeScript
0.357
suggestion
105
40
51
false
Upgrade notification stimulus
9,801
wagtail/wagtail
16,097
Python
lb-
Lovelyfin00
that matches the slug on any site. """ page = None try: site = Site.find_for_request(context["request"]) current_site = site except KeyError: # No site object found - allow the fallback below to take place. pass else: if current_site is not None: ...
I think this has been changed by accident
First tries to find a page on the current site. If that fails or a request is not available in the context, then returns the URL for the first page that matches the slug on any site. """ page = None try: site = Site.find_for_request(context["request"]) current_site = site e...
@@ -76,7 +76,7 @@ def slugurl(context, slug): @register.simple_tag def wagtail_version(): - return __version__ + return "2.10"
wagtail/templatetags/wagtailcore_tags.py
26
Python
0.143
suggestion
42
51
51
false
Upgrade notification stimulus
9,801
wagtail/wagtail
16,097
Python
lb-
Lovelyfin00
from: 'wagtail/images/static_src/', to: 'wagtail/images/static/', globOptions: { ignore: ['**/{app,scss}/**', '*.{css,txt}'] }, }, { from: 'wagtail/search/static_src/', to: 'wagtail/search/static/', globOptions: { ignore: ['**/{...
This line should probably not be removed - can you re-add it.
}, { from: 'wagtail/users/static_src/', to: 'wagtail/users/static/', globOptions: { ignore: ['**/{app,scss}/**', '*.{css,txt}'] }, }, { from: 'wagtail/contrib/settings/static_src/', to: 'wagtail/contrib/settings/static/'...
@@ -222,7 +222,6 @@ module.exports = function exports(env, argv) { { test: /\.(js|ts)x?$/, loader: 'ts-loader', - exclude: /node_modules/,
client/webpack.config.js
26
JavaScript
0.286
suggestion
62
51
51
false
Upgrade notification stimulus
9,801
wagtail/wagtail
16,097
Python
lb-
Lovelyfin00
} }; // Delay snapshotting the form’s data to avoid race conditions with form widgets that might process the values. // User interaction with the form within that delay also won’t trigger the confirmation message. if (!alwaysDirty) { setTimeout(() => { const initialFormData = new FormData($form[0...
Be careful here with this change. The for loop return statement on line 160 below is actually returning from this function - when you use the forEach the rest of the results still go through the mapping. You either need to set a variable above the loop like `let isValidNode = false;` and then set the variable t...
const updateIsDirty = () => { const previousIsDirty = isDirty; isDirty = isFormDirty(); if (previousIsDirty !== isDirty) { updateCallback(isDirty, isCommentsDirty); } }; // Delay snapshotting the form’s data to avoid race conditions with form widgets that might process the values. // Use...
@@ -150,27 +152,26 @@ function enableDirtyFormCheck(formSelector, options) { $form.on('change keyup', updateDirtyCheck).trigger('change'); const validInputNodeInList = (nodeList) => { - for (const node of nodeList) { + nodeList.forEach((node) => /* eslint-disable-line consistent-return */ ...
client/src/entrypoints/admin/core.js
26
JavaScript
0.643
suggestion
489
51
51
false
removed legacyCode rules and the files being overridden and fixed lin…
9,805
wagtail/wagtail
16,097
Python
lb-
Lovelyfin00
let updateFooterTextTimeout = -1; window.updateFooterSaveWarning = (formDirty, commentsDirty) => { const warningContainer = $('[data-unsaved-warning]'); const warnings = warningContainer.find('[data-unsaved-type]'); const anyDirty = formDirty || commentsDirty; const typeVisibility = { all: formDirty && comm...
We follow the Airbnb styleguide (https://github.com/airbnb/javascript), which encourages always placing comments on their own separate line, preceding what the comment is for. So in this case: ```suggestion // eslint-disable-next-line no-param-reassign warning.hidden = !visible; ```
let updateFooterTextTimeout = -1; window.updateFooterSaveWarning = (formDirty, commentsDirty) => { const warningContainer = $('[data-unsaved-warning]'); const warnings = warningContainer.find('[data-unsaved-type]'); const anyDirty = formDirty || commentsDirty; const typeVisibility = { all: formDirty && comm...
@@ -133,10 +133,10 @@ window.updateFooterSaveWarning = (formDirty, commentsDirty) => { } clearTimeout(updateFooterTextTimeout); const updateWarnings = () => { - for (const warning of warnings) { + warnings.forEach((warning) => { const visible = typeVisibility[warning.dataset.unsavedType]; - w...
client/src/entrypoints/admin/page-editor.js
26
JavaScript
0.786
suggestion
300
36
37
false
removed legacyCode rules and the files being overridden and fixed lin…
9,805
wagtail/wagtail
16,097
Python
thibaudcolas
Lovelyfin00
self.assertEqual(self.image.focal_point_y, 250) self.assertEqual(self.image.focal_point_width, 100) self.assertEqual(self.image.focal_point_height, 200) self.image.set_focal_point(None) self.assertIsNone(self.image.focal_point_x) self.assertIsNone(self.image.focal_point...
```suggestion # Simulate the case is which the storage is set dynamically ```
self.image.focal_point_y = 200 self.image.focal_point_width = 50 self.image.focal_point_height = 20 self.assertTrue(self.image.has_focal_point()) def test_set_focal_point(self): self.assertIsNone(self.image.focal_point_x) self.assertIsNone(self.image.focal_point_y) ...
@@ -102,6 +117,18 @@ def test_is_stored_locally(self): def test_is_stored_locally_with_external_storage(self): self.assertFalse(self.image.is_stored_locally()) + @override_settings( + DEFAULT_FILE_STORAGE="wagtail.test.dummy_external_storage.DummyExternalStorage" + ) + def test_reopen_ba...
wagtail/images/tests/test_models.py
26
Python
0.571
suggestion
87
51
51
false
correct the way of getting the storage of an image/document (#9904)
10,412
wagtail/wagtail
16,097
Python
RealOrangeOne
engAmirEng
self.assertIsNone(self.image.focal_point_x) self.assertIsNone(self.image.focal_point_y) self.assertIsNone(self.image.focal_point_width) self.assertIsNone(self.image.focal_point_height) def test_is_stored_locally(self): self.assertTrue(self.image.is_stored_locally()) @o...
Nit: Use `assertIsInstance` rather than comparing the class directly ```suggestion self.assertIsInstance(f, AnotherDummyExternalStorageFile) ```
def test_set_focal_point(self): self.assertIsNone(self.image.focal_point_x) self.assertIsNone(self.image.focal_point_y) self.assertIsNone(self.image.focal_point_width) self.assertIsNone(self.image.focal_point_height) self.image.set_focal_point(Rect(100, 150, 200, 350)) ...
@@ -102,6 +117,18 @@ def test_is_stored_locally(self): def test_is_stored_locally_with_external_storage(self): self.assertFalse(self.image.is_stored_locally()) + @override_settings( + DEFAULT_FILE_STORAGE="wagtail.test.dummy_external_storage.DummyExternalStorage" + ) + def test_reopen_ba...
wagtail/images/tests/test_models.py
26
Python
0.786
suggestion
163
51
51
false
correct the way of getting the storage of an image/document (#9904)
10,412
wagtail/wagtail
16,097
Python
RealOrangeOne
engAmirEng
def test_reopen_based_on_storage_that_is_dynamically_set(self): self.image.file.close() # Simulate the case is witch the storage is set dynamically with mock.patch.object( self.image.file, "storage", AnotherDummyExternalStorage() ): with self.image.open_file()...
Question: Is there a need to mock the `storage` here if `DEFAULT_FILE_STORAGE` is set? Can one of these be removed?
self.assertIsNone(self.image.focal_point_width) self.assertIsNone(self.image.focal_point_height) def test_is_stored_locally(self): self.assertTrue(self.image.is_stored_locally()) @override_settings( STORAGES={ **settings.STORAGES, "default": { ...
@@ -102,6 +117,18 @@ def test_is_stored_locally(self): def test_is_stored_locally_with_external_storage(self): self.assertFalse(self.image.is_stored_locally()) + @override_settings( + DEFAULT_FILE_STORAGE="wagtail.test.dummy_external_storage.DummyExternalStorage" + ) + def test_reopen_ba...
wagtail/images/tests/test_models.py
26
Python
0.571
question
115
51
51
false
correct the way of getting the storage of an image/document (#9904)
10,412
wagtail/wagtail
16,097
Python
RealOrangeOne
engAmirEng
import json import warnings from django.core.serializers.json import DjangoJSONEncoder from django.forms import Media, widgets from django.utils.encoding import force_str from django.utils.functional import Promise, cached_property from wagtail.admin.rich_text.converters.contentstate import ContentstateConverter from...
`DjangoJSONEncoder` already handles lazy strings: https://github.com/django/django/blob/8eca4077f60fa0705ecfd9437c9ceaeef7a3808b/django/core/serializers/json.py#L111-L112
import json import warnings from django.core.serializers.json import DjangoJSONEncoder from django.forms import Media, widgets from django.utils.functional import cached_property from wagtail.admin.rich_text.converters.contentstate import ContentstateConverter from wagtail.admin.staticfiles import versioned_static fr...
@@ -11,6 +13,13 @@ from wagtail.widget_adapters import WidgetAdapter +class LazyEncoder(DjangoJSONEncoder): + def default(self, obj): + if isinstance(obj, Promise): + return force_str(obj) + return super().default(obj)
wagtail/admin/rich_text/editors/draftail/__init__.py
20
Python
0.643
suggestion
170
45
45
false
Take preferred language into account in JavaScriptCatalog view
11,075
wagtail/wagtail
16,097
Python
laymonage
bbliem
"SINGULAR": _("1 item selected"), "PLURAL": _("%(objects)s items selected"), "ALL": _("All %(objects)s items on this screen selected"), "ALL_IN_LISTING": _("All items in listing selected"), }, }, } def get_available_admin_language...
We can simplify the signature a bit by dropping `user` and get it from `request.user`
"ALL": _("All %(objects)s items on this screen selected"), "ALL_IN_LISTING": _("All items in listing selected"), }, }, } def get_available_admin_languages(): return getattr( settings, "WAGTAILADMIN_PERMITTED_LANGUAGES", WAGTAILADMIN_PROVIDED_LANGUAGE...
@@ -117,3 +122,40 @@ def get_available_admin_time_zones(): return getattr( settings, "WAGTAIL_USER_TIME_ZONES", sorted(zoneinfo.available_timezones()) ) + + +def get_localized_response(user, view_func, request, *args, **kwargs):
wagtail/admin/localization.py
26
Python
0.429
refactor
85
51
51
false
Take preferred language into account in JavaScriptCatalog view
11,075
wagtail/wagtail
16,097
Python
laymonage
bbliem
StreamFieldBlockPreview.as_view(), name="wagtailadmin_block_preview", ), ] # Import additional urlpatterns from any apps that define a register_admin_urls hook for fn in hooks.get_hooks("register_admin_urls"): urls = fn() if urls: urlpatterns += urls # Add "wagtailadmin.access_ad...
We should probably put this in its own file in `wagtail.admin.views`, just so that we don't pollute the urls file with ad-hoc views.
name="wagtailadmin_block_preview", ), ] # Import additional urlpatterns from any apps that define a register_admin_urls hook for fn in hooks.get_hooks("register_admin_urls"): urls = fn() if urls: urlpatterns += urls # Add "wagtailadmin.access_admin" permission check urlpatterns = decorat...
@@ -138,6 +139,17 @@ urlpatterns = decorate_urlpatterns(urlpatterns, require_admin_access) +def localized_js_catalog(): + js_catalog_view = JavaScriptCatalog.as_view(packages=["wagtail.admin"]) + + def view(request, *args, **kwargs): + return get_localized_response( + request.user, js_catal...
wagtail/admin/urls/__init__.py
26
Python
0.571
suggestion
132
51
51
false
Take preferred language into account in JavaScriptCatalog view
11,075
wagtail/wagtail
16,097
Python
laymonage
bbliem
"draftail", "hr", draftail_features.BooleanFeature("enableHorizontalRule") ) features.register_converter_rule( "contentstate", "hr", { "from_database_format": { "hr": HorizontalRuleHandler(), }, "to_database_format": { ...
I reverted your change to use dedicated strings for each heading for now. I like the idea compared to the alternatives, but it is going to be quite a bit of work to backport the fix to the release branches, as we'll need to update the translation strings too. I think we should focus on getting the `JavaScriptCatalog...
features.register_editor_plugin( "draftail", "hr", draftail_features.BooleanFeature("enableHorizontalRule") ) features.register_converter_rule( "contentstate", "hr", { "from_database_format": { "hr": HorizontalRuleHandler(), }, ...
@@ -495,7 +494,8 @@ def register_core_features(features): { "icon": "h1", "type": "header-one", - "description": gettext("Heading %(level)d") % {"level": 1}, + # FIXME: interpolation causes immediate evaluation + "description": ...
wagtail/admin/wagtail_hooks.py
26
Python
0.643
suggestion
498
51
51
false
Take preferred language into account in JavaScriptCatalog view
11,075
wagtail/wagtail
16,097
Python
laymonage
bbliem
def get_available_admin_languages(): return getattr( settings, "WAGTAILADMIN_PERMITTED_LANGUAGES", WAGTAILADMIN_PROVIDED_LANGUAGES ) @functools.cache def get_available_admin_time_zones(): if not settings.USE_TZ: return [] return getattr( settings, "WAGTAIL_USER_TIME_ZONES", s...
I wonder if `LogContext` should be applied here or kept in `require_admin_access`. The latter would be more appropriate (as it's not related to localization), but the changes wouldn't be a 1:1 cut-paste from the original code.
return getattr( settings, "WAGTAILADMIN_PERMITTED_LANGUAGES", WAGTAILADMIN_PROVIDED_LANGUAGES ) @functools.cache def get_available_admin_time_zones(): if not settings.USE_TZ: return [] return getattr( settings, "WAGTAIL_USER_TIME_ZONES", sorted(zoneinfo.available_timezones()) ...
@@ -117,3 +122,41 @@ def get_available_admin_time_zones(): return getattr( settings, "WAGTAIL_USER_TIME_ZONES", sorted(zoneinfo.available_timezones()) ) + + +def get_localized_response(view_func, request, *args, **kwargs): + user = request.user + preferred_language = None + if hasattr(user, ...
wagtail/admin/localization.py
26
Python
0.643
suggestion
226
51
51
false
Take preferred language into account in JavaScriptCatalog view
11,075
wagtail/wagtail
16,097
Python
laymonage
bbliem
Redirect.objects.create( old_path="/hello-world", site=self.example_site, redirect_link="https://www.example.com/hello-world/", ) Redirect.objects.create( old_path="/good-work", site=self.example_site, redirect_l...
We should add a test for just the index listing also, using `find` is not the only thing added with this new API endpoint
Redirect.objects.create( old_path="/hello-world", site=self.example_site, redirect_link="https://www.example.com/hello-world/", ) Redirect.objects.create( old_path="/good-work", site=self.example_site, redirect_link="https...
@@ -0,0 +1,84 @@ +from django.test import TestCase +from django.urls import reverse + +from wagtail.contrib.redirects.models import Redirect +from wagtail.models import Page, Site + + +class TestRedirectsAPI(TestCase): + def setUp(self): + self.example_home = Page.objects.get(slug="home").add_sibling...
wagtail/contrib/redirects/tests/test_redirects_api.py
26
Python
0.571
suggestion
121
51
51
false
Add Redirect API
11,510
wagtail/wagtail
16,097
Python
lb-
rohitsrma
old_path="/hello-world", site=self.example_site, redirect_link="https://www.example.com/hello-world/", ) Redirect.objects.create( old_path="/good-work", site=self.example_site, redirect_link="https://www.example.com/hello-w...
Normally we avoid too much abstraction in unit tests early, I would recommend putting this code (copy/paste) into the individual tests. It feels a bit odd but often in unit tests a bit of duplication can help make the tests easier to understand. When it gets excessive (e.g. maybe 5+ copy/paste) then we try to abs...
old_path="/hello-world", site=self.example_site, redirect_link="https://www.example.com/hello-world/", ) Redirect.objects.create( old_path="/good-work", site=self.example_site, redirect_link="https://www.example.com/hello-world/", ...
@@ -0,0 +1,84 @@ +from django.test import TestCase +from django.urls import reverse + +from wagtail.contrib.redirects.models import Redirect +from wagtail.models import Page, Site + + +class TestRedirectsAPI(TestCase): + def setUp(self): + self.example_home = Page.objects.get(slug="home").add_sibling...
wagtail/contrib/redirects/tests/test_redirects_api.py
26
Python
0.5
refactor
339
51
51
false
Add Redirect API
11,510
wagtail/wagtail
16,097
Python
lb-
rohitsrma
@register.simple_tag() def workflow_status_with_date(workflow_state): translation_context = { "finished_at": naturaltime(workflow_state.current_task_state.finished_at), "started_at": naturaltime(workflow_state.current_task_state.started_at), "task_name": workflow_state.current_task_state.t...
```suggestion "mod": "⌘" if is_mac else "Ctrl", ``` Just realised we should be calling this `mod` not `meta` - mod seems to be the convention for things like this. The template would also need to be updated.
@register.simple_tag() def workflow_status_with_date(workflow_state): translation_context = { "finished_at": naturaltime(workflow_state.current_task_state.finished_at), "started_at": naturaltime(workflow_state.current_task_state.started_at), "task_name": workflow_state.current_task_state.t...
@@ -1296,6 +1297,15 @@ def workflow_status_with_date(workflow_state): return _("%(status_display)s %(task_name)s %(started_at)s") % translation_context +@register.inclusion_tag("wagtailadmin/shared/keyboard_shortcuts_dialog.html", takes_context=True) +def keyboard_shortcuts_dialog(context): + user_agent = c...
wagtail/admin/templatetags/wagtailadmin_tags.py
26
Python
0.857
suggestion
225
47
51
false
Add a basic keyboard shortcuts overview dialog
11,717
wagtail/wagtail
16,097
Python
lb-
kituuu
def workflow_status_with_date(workflow_state): translation_context = { "finished_at": naturaltime(workflow_state.current_task_state.finished_at), "started_at": naturaltime(workflow_state.current_task_state.started_at), "task_name": workflow_state.current_task_state.task.name, "status...
Instead of repeating the logic, we can extract this to a variable, e.g. ```py modifier = "⌘" if is_mac else "Ctrl" ``` and in this case I think the keys should be in snake case, e.g. ```suggestion {"label": "Save", "shortcut": f"{modifier} + s"}, ```
"status_display": workflow_state.get_status_display, } if workflow_state.status == "needs_changes": return _("Changes requested %(finished_at)s") % translation_context if workflow_state.status == "in_progress": return _("Sent to %(task_name)s %(started_at)s") % translation_context ...
@@ -1301,6 +1302,55 @@ def workflow_status_with_date(workflow_state): return _("%(status_display)s %(task_name)s %(started_at)s") % translation_context +@register.inclusion_tag( + "wagtailadmin/shared/keyboard_shortcuts_dialog.html", takes_context=True +) +def keyboard_shortcuts_dialog(context): + user_a...
wagtail/admin/templatetags/wagtailadmin_tags.py
26
Python
0.857
refactor
275
51
51
false
Add a basic keyboard shortcuts overview dialog
11,717
wagtail/wagtail
16,097
Python
laymonage
kituuu
translation_context = { "finished_at": naturaltime(workflow_state.current_task_state.finished_at), "started_at": naturaltime(workflow_state.current_task_state.started_at), "task_name": workflow_state.current_task_state.task.name, "status_display": workflow_state.get_status_display, ...
Each of these labels needs to support being translated, labels only, not the shortcut. ```suggestion {"label": _("Save"), "shortcut": f"{modifier} + s"}, ```
} if workflow_state.status == "needs_changes": return _("Changes requested %(finished_at)s") % translation_context if workflow_state.status == "in_progress": return _("Sent to %(task_name)s %(started_at)s") % translation_context return _("%(status_display)s %(task_name)s %(started_at)...
@@ -1301,6 +1302,56 @@ def workflow_status_with_date(workflow_state): return _("%(status_display)s %(task_name)s %(started_at)s") % translation_context +@register.inclusion_tag( + "wagtailadmin/shared/keyboard_shortcuts_dialog.html", takes_context=True +) +def keyboard_shortcuts_dialog(context): + user_a...
wagtail/admin/templatetags/wagtailadmin_tags.py
26
Python
0.714
suggestion
176
51
51
false
Add a basic keyboard shortcuts overview dialog
11,717
wagtail/wagtail
16,097
Python
lb-
kituuu
def workflow_status_with_date(workflow_state): translation_context = { "finished_at": naturaltime(workflow_state.current_task_state.finished_at), "started_at": naturaltime(workflow_state.current_task_state.started_at), "task_name": workflow_state.current_task_state.task.name, "status...
```suggestion ('actions', _("Actions")): [ ``` Each heading needs to be translated also. I actually recommend we maybe use a tuple here, it will help us generate a unique ID for each group in the DOM and will be useful for code.
"status_display": workflow_state.get_status_display, } if workflow_state.status == "needs_changes": return _("Changes requested %(finished_at)s") % translation_context if workflow_state.status == "in_progress": return _("Sent to %(task_name)s %(started_at)s") % translation_context ...
@@ -1301,6 +1302,56 @@ def workflow_status_with_date(workflow_state): return _("%(status_display)s %(task_name)s %(started_at)s") % translation_context +@register.inclusion_tag( + "wagtailadmin/shared/keyboard_shortcuts_dialog.html", takes_context=True +) +def keyboard_shortcuts_dialog(context): + user_a...
wagtail/admin/templatetags/wagtailadmin_tags.py
26
Python
0.857
suggestion
244
51
51
false
Add a basic keyboard shortcuts overview dialog
11,717
wagtail/wagtail
16,097
Python
lb-
kituuu
@register.simple_tag() def workflow_status_with_date(workflow_state): translation_context = { "finished_at": naturaltime(workflow_state.current_task_state.finished_at), "started_at": naturaltime(workflow_state.current_task_state.started_at), "task_name": workflow_state.current_task_state.tas...
If you are going to give this to the context as `shortcuts`, just use the same name for the variable, no need to add confusion to the code by giving things different names. ```suggestion shortcuts = { ```
"task_name": workflow_state.current_task_state.task.name, "status_display": workflow_state.get_status_display, } if workflow_state.status == "needs_changes": return _("Changes requested %(finished_at)s") % translation_context if workflow_state.status == "in_progress": retur...
@@ -1301,6 +1302,56 @@ def workflow_status_with_date(workflow_state): return _("%(status_display)s %(task_name)s %(started_at)s") % translation_context +@register.inclusion_tag( + "wagtailadmin/shared/keyboard_shortcuts_dialog.html", takes_context=True +) +def keyboard_shortcuts_dialog(context): + user_a...
wagtail/admin/templatetags/wagtailadmin_tags.py
26
Python
0.857
suggestion
215
51
51
false
Add a basic keyboard shortcuts overview dialog
11,717
wagtail/wagtail
16,097
Python
lb-
kituuu
"task_name": workflow_state.current_task_state.task.name, "status_display": workflow_state.get_status_display, } if workflow_state.status == "needs_changes": return _("Changes requested %(finished_at)s") % translation_context if workflow_state.status == "in_progress": retur...
Let's move common actions above the 'actions'.
return _("Changes requested %(finished_at)s") % translation_context if workflow_state.status == "in_progress": return _("Sent to %(task_name)s %(started_at)s") % translation_context return _("%(status_display)s %(task_name)s %(started_at)s") % translation_context @register.inclusion_tag( ...
@@ -1301,6 +1302,56 @@ def workflow_status_with_date(workflow_state): return _("%(status_display)s %(task_name)s %(started_at)s") % translation_context +@register.inclusion_tag( + "wagtailadmin/shared/keyboard_shortcuts_dialog.html", takes_context=True +) +def keyboard_shortcuts_dialog(context): + user_a...
wagtail/admin/templatetags/wagtailadmin_tags.py
26
Python
0.143
suggestion
46
51
51
false
Add a basic keyboard shortcuts overview dialog
11,717
wagtail/wagtail
16,097
Python
lb-
kituuu
def workflow_status_with_date(workflow_state): translation_context = { "finished_at": naturaltime(workflow_state.current_task_state.finished_at), "started_at": naturaltime(workflow_state.current_task_state.started_at), "task_name": workflow_state.current_task_state.task.name, "status...
Let's rename this 'Page editing actions' instead, and move under the common actions.
"status_display": workflow_state.get_status_display, } if workflow_state.status == "needs_changes": return _("Changes requested %(finished_at)s") % translation_context if workflow_state.status == "in_progress": return _("Sent to %(task_name)s %(started_at)s") % translation_context ...
@@ -1301,6 +1302,56 @@ def workflow_status_with_date(workflow_state): return _("%(status_display)s %(task_name)s %(started_at)s") % translation_context +@register.inclusion_tag( + "wagtailadmin/shared/keyboard_shortcuts_dialog.html", takes_context=True +) +def keyboard_shortcuts_dialog(context): + user_a...
wagtail/admin/templatetags/wagtailadmin_tags.py
26
Python
0.286
suggestion
84
51
51
false
Add a basic keyboard shortcuts overview dialog
11,717
wagtail/wagtail
16,097
Python
lb-
kituuu
self.label, self.url, start_page.id, icon_name=self.icon_name, classname=self.classname, ) else: return super().render_component(request) @hooks.register("register_help_menu_item") def register_keyboard_sho...
Please can this be moved to around line 1016 - after `register_editors_guide_menu_item`. This way the code order will follow the visual rendering ordering the sidebar.
self.label, self.url, start_page.id, icon_name=self.icon_name, classname=self.classname, ) else: return super().render_component(request) @hooks.register("register_admin_menu_item") def register_explorer_me...
@@ -96,6 +96,23 @@ def render_component(self, request): return super().render_component(request) +@hooks.register("register_help_menu_item") +def register_keyboard_shortcuts_menu_item(): + return MenuItem( + _("Shortcuts"), + icon_name="regex", + order=1200, + attrs={ + ...
wagtail/admin/wagtail_hooks.py
26
Python
0.571
suggestion
169
51
51
false
Add a basic keyboard shortcuts overview dialog
11,717
wagtail/wagtail
16,097
Python
lb-
kituuu
return _("Changes requested %(finished_at)s") % translation_context if workflow_state.status == "in_progress": return _("Sent to %(task_name)s %(started_at)s") % translation_context return _("%(status_display)s %(task_name)s %(started_at)s") % translation_context @register.inclusion_tag( ...
The default Redo on Mac is `SHIFT + ⌘ + Z`, this one opens up history in Chrome. ;) Mac also does't spell out shift but uses a arrow up icon. Not sure how close we want to stay to OS style icons/wording.
return _("Changes requested %(finished_at)s") % translation_context if workflow_state.status == "in_progress": return _("Sent to %(task_name)s %(started_at)s") % translation_context return _("%(status_display)s %(task_name)s %(started_at)s") % translation_context @register.inclusion_tag( ...
@@ -1296,6 +1297,56 @@ def workflow_status_with_date(workflow_state): return _("%(status_display)s %(task_name)s %(started_at)s") % translation_context +@register.inclusion_tag( + "wagtailadmin/shared/keyboard_shortcuts_dialog.html", takes_context=True +) +def keyboard_shortcuts_dialog(context): + user_a...
wagtail/admin/templatetags/wagtailadmin_tags.py
26
Python
0.643
nitpick
207
51
51
false
Add a basic keyboard shortcuts overview dialog
11,717
wagtail/wagtail
16,097
Python
allcaps
kituuu
"status_display": workflow_state.get_status_display, } if workflow_state.status == "needs_changes": return _("Changes requested %(finished_at)s") % translation_context if workflow_state.status == "in_progress": return _("Sent to %(task_name)s %(started_at)s") % translation_context ...
The mac wording for this label is "Paste and Match Style". Not sure how close we want to stay to OS style icons/wording.
"status_display": workflow_state.get_status_display, } if workflow_state.status == "needs_changes": return _("Changes requested %(finished_at)s") % translation_context if workflow_state.status == "in_progress": return _("Sent to %(task_name)s %(started_at)s") % translation_context ...
@@ -1296,6 +1297,56 @@ def workflow_status_with_date(workflow_state): return _("%(status_display)s %(task_name)s %(started_at)s") % translation_context +@register.inclusion_tag( + "wagtailadmin/shared/keyboard_shortcuts_dialog.html", takes_context=True +) +def keyboard_shortcuts_dialog(context): + user_a...
wagtail/admin/templatetags/wagtailadmin_tags.py
26
Python
0.357
nitpick
123
51
51
false
Add a basic keyboard shortcuts overview dialog
11,717
wagtail/wagtail
16,097
Python
allcaps
kituuu
return _("Sent to %(task_name)s %(started_at)s") % translation_context return _("%(status_display)s %(task_name)s %(started_at)s") % translation_context @register.inclusion_tag( "wagtailadmin/shared/keyboard_shortcuts_dialog.html", takes_context=True ) def keyboard_shortcuts_dialog(context): user...
I didn't know about `⌘ + s` :clap: Models (snippets) are saved, but pages `Save draft`. Maybe the label should be `Save (draft)`? This shortcut overrides the default browser behaviour. And in this specific case, that seems okay. Saving HTML is not a common thing to do. Overriding OS/browser shortcuts is something...
return _("Sent to %(task_name)s %(started_at)s") % translation_context return _("%(status_display)s %(task_name)s %(started_at)s") % translation_context @register.inclusion_tag( "wagtailadmin/shared/keyboard_shortcuts_dialog.html", takes_context=True, ) def keyboard_shortcuts_dialog(context): ...
@@ -1296,6 +1297,56 @@ def workflow_status_with_date(workflow_state): return _("%(status_display)s %(task_name)s %(started_at)s") % translation_context +@register.inclusion_tag( + "wagtailadmin/shared/keyboard_shortcuts_dialog.html", takes_context=True +) +def keyboard_shortcuts_dialog(context): + user_a...
wagtail/admin/templatetags/wagtailadmin_tags.py
26
Python
0.643
suggestion
559
51
51
false
Add a basic keyboard shortcuts overview dialog
11,717
wagtail/wagtail
16,097
Python
allcaps
kituuu
order=1100, attrs={"target": "_blank", "rel": "noreferrer"}, name="editor-guide", ) @hooks.register("register_help_menu_item") def register_keyboard_shortcuts_menu_item(): return MenuItem( _("Shortcuts"), icon_name="regex", order=1200, attrs={ ...
It would be very cool if opening the modal could be a shortcut too. `command + /` is common.
order=1100, attrs={"target": "_blank", "rel": "noreferrer"}, name="editor-guide", ) @hooks.register("register_help_menu_item") def register_keyboard_shortcuts_menu_item(): """ Triggers the keyboard shortcuts dialog to open when clicked while preventing the default link click ac...
@@ -998,6 +998,23 @@ def register_editors_guide_menu_item(): ) +@hooks.register("register_help_menu_item") +def register_keyboard_shortcuts_menu_item(): + return MenuItem( + _("Shortcuts"), + icon_name="regex", + order=1200, + attrs={ + "role": "button", + "...
wagtail/admin/wagtail_hooks.py
26
Python
0.429
suggestion
92
51
51
false
Add a basic keyboard shortcuts overview dialog
11,717
wagtail/wagtail
16,097
Python
allcaps
kituuu
return _("Sent to %(task_name)s %(started_at)s") % translation_context return _("%(status_display)s %(task_name)s %(started_at)s") % translation_context @register.inclusion_tag( "wagtailadmin/shared/keyboard_shortcuts_dialog.html", takes_context=True ) def keyboard_shortcuts_dialog(context): user...
```suggestion {"label": _("Save changes"), "shortcut": f"{modifier} + s"}, ``` How about this @allcaps - keeps it generic across usage.
return _("Sent to %(task_name)s %(started_at)s") % translation_context return _("%(status_display)s %(task_name)s %(started_at)s") % translation_context @register.inclusion_tag( "wagtailadmin/shared/keyboard_shortcuts_dialog.html", takes_context=True, ) def keyboard_shortcuts_dialog(context): ...
@@ -1296,6 +1297,56 @@ def workflow_status_with_date(workflow_state): return _("%(status_display)s %(task_name)s %(started_at)s") % translation_context +@register.inclusion_tag( + "wagtailadmin/shared/keyboard_shortcuts_dialog.html", takes_context=True +) +def keyboard_shortcuts_dialog(context): + user_a...
wagtail/admin/templatetags/wagtailadmin_tags.py
26
Python
0.786
suggestion
152
51
51
false
Add a basic keyboard shortcuts overview dialog
11,717
wagtail/wagtail
16,097
Python
lb-
kituuu
return _("Changes requested %(finished_at)s") % translation_context if workflow_state.status == "in_progress": return _("Sent to %(task_name)s %(started_at)s") % translation_context return _("%(status_display)s %(task_name)s %(started_at)s") % translation_context @register.inclusion_tag( ...
```suggestion {"label": _("Redo"), "shortcut": f"{modifier} + Shift + z" if is_mac else f"{modifier} + y"}, ```
return _("Changes requested %(finished_at)s") % translation_context if workflow_state.status == "in_progress": return _("Sent to %(task_name)s %(started_at)s") % translation_context return _("%(status_display)s %(task_name)s %(started_at)s") % translation_context @register.inclusion_tag( ...
@@ -1296,6 +1297,56 @@ def workflow_status_with_date(workflow_state): return _("%(status_display)s %(task_name)s %(started_at)s") % translation_context +@register.inclusion_tag( + "wagtailadmin/shared/keyboard_shortcuts_dialog.html", takes_context=True +) +def keyboard_shortcuts_dialog(context): + user_a...
wagtail/admin/templatetags/wagtailadmin_tags.py
26
Python
0.714
suggestion
126
51
51
false
Add a basic keyboard shortcuts overview dialog
11,717
wagtail/wagtail
16,097
Python
lb-
kituuu
@register.simple_tag() def workflow_status_with_date(workflow_state): translation_context = { "finished_at": naturaltime(workflow_state.current_task_state.finished_at), "started_at": naturaltime(workflow_state.current_task_state.started_at), "task_name": workflow_state.current_task_state.tas...
Sorry for the back and forth on structure here but a few changes I will do when merging but wanted to explain. 1. Let's use tuples for the shortcuts -> `{"label": _("Copy"), "shortcut": f"{modifier} + c"}` would be `(_("Copy"), f"{modifier} + c")`. This is a bit easier to read when looking at a lot of these. 2. Le...
@register.simple_tag() def workflow_status_with_date(workflow_state): translation_context = { "finished_at": naturaltime(workflow_state.current_task_state.finished_at), "started_at": naturaltime(workflow_state.current_task_state.started_at), "task_name": workflow_state.current_task_state.tas...
@@ -1296,6 +1297,61 @@ def workflow_status_with_date(workflow_state): return _("%(status_display)s %(task_name)s %(started_at)s") % translation_context +@register.inclusion_tag( + "wagtailadmin/shared/keyboard_shortcuts_dialog.html", takes_context=True +) +def keyboard_shortcuts_dialog(context): + user_a...
wagtail/admin/templatetags/wagtailadmin_tags.py
26
Python
0.857
suggestion
878
51
51
false
Add a basic keyboard shortcuts overview dialog
11,717
wagtail/wagtail
16,097
Python
lb-
kituuu
def register_whats_new_in_wagtail_version_menu_item(): version = "6.1" return DismissibleMenuItem( _("What's new in Wagtail %(version)s") % {"version": version}, wagtail_feature_release_whats_new_link(), icon_name="help", order=1000, attrs={"target": "_blank", "rel": "nor...
Let's add a simple docstring here, helps for future context. I can add this when merging. ```suggestion def register_keyboard_shortcuts_menu_item(): """ Triggers the keyboard shortcuts dialog to open when clicked while preventing the default link click action. """ ```
def register_whats_new_in_wagtail_version_menu_item(): version = "6.1" return DismissibleMenuItem( _("What's new in Wagtail %(version)s") % {"version": version}, wagtail_feature_release_whats_new_link(), icon_name="help", order=1000, attrs={"target": "_blank", "rel": "nor...
@@ -998,6 +998,23 @@ def register_editors_guide_menu_item(): ) +@hooks.register("register_help_menu_item") +def register_keyboard_shortcuts_menu_item():
wagtail/admin/wagtail_hooks.py
26
Python
0.786
suggestion
295
51
51
false
Add a basic keyboard shortcuts overview dialog
11,717
wagtail/wagtail
16,097
Python
lb-
kituuu
self.assertEqual(christmas_page.url, "/site/events/christmas/") self.assertEqual( christmas_page.relative_url(default_site), "/site/events/christmas/" ) self.assertEqual(christmas_page.get_site(), default_site) @override_settings(ROOT_URLCONF="wagtail.test.headless_urls"...
Since we're only optimising internals here, I was thinking we could probably get away with adding a `self.assertNumQueries()` to an existing test. What do you think @Nigel2392?
christmas_page.full_url, "http://events.example.com/christmas/" ) self.assertEqual(christmas_page.url, "http://events.example.com/christmas/") self.assertEqual( christmas_page.relative_url(default_site), "http://events.example.com/christmas/", ) ...
@@ -442,6 +442,20 @@ def test_request_routing(self): (found_page, args, kwargs) = homepage.route(request, ["events", "christmas"]) self.assertEqual(found_page, christmas_page) + def test_cached_parent_obj_set(self):
wagtail/tests/test_page_model.py
26
Python
0.571
question
177
51
51
false
Update page routing, add tests
11,737
wagtail/wagtail
16,097
Python
ababic
Nigel2392
import datetime import unittest from unittest.mock import Mock from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.auth.models import AnonymousUser, Group from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ValidationError from d...
I wonder if this one could be optimised somewhat, for example: just take the root page, set `_cached_parent_obj` to some nonsense variable, then check `get_parent()` returns the nonsense variable. The assertion failure message could even say something super obvious, like: > Page.get_parent() no longer uses _cached_par...
fixtures = ["test.json"] def setUp(self): self.page = Page.objects.last() self.other_page = Page.objects.first() def test_cache_key_consistent(self): self.assertEqual(self.page.cache_key, self.page.cache_key) self.assertEqual(self.other_page.cache_key, self.other_page.cache...
@@ -3917,3 +3931,20 @@ def test_changes_when_slug_changes(self): self.page.slug = "something-else" self.page.save() self.assertNotEqual(self.page.cache_key, original_cache_key) + + +class TestPageCachedParentObjExists(TestCase): + fixtures = ["test.json"] + + def test_cached_parent_obj_...
wagtail/tests/test_page_model.py
26
Python
0.643
bug
432
3,951
39
false
Update page routing, add tests
11,737
wagtail/wagtail
16,097
Python
ababic
Nigel2392
edit_handler = TabbedInterface( [ ObjectList(advert_panels, heading="Advert"), ObjectList( other_panels, heading="Other", help_text="Other panels help text" ), ], help_text="Top-level help text", ) def __str__(self): retur...
Thanks, but we don't need a new model for this, let's just reuse an existing one. Adding a new model would add additional overhead as that's yet another migration to run and another table to create on the database.
edit_handler = TabbedInterface( [ ObjectList(advert_panels, heading="Advert"), ObjectList( other_panels, heading="Other", help_text="Other panels help text" ), ], help_text="Top-level help text", ) def __str__(self): retur...
@@ -1011,6 +1011,28 @@ class Meta: register_snippet(AdvertWithTabbedInterface) +class AdvertManager(models.Manager): + pass + + +class AdvertWithCustomManager(models.Model):
wagtail/test/testapp/models.py
26
Python
0.5
suggestion
214
51
51
false
Use `default_manager` instead of `objects` in `ModelIndexView`
11,766
wagtail/wagtail
16,097
Python
laymonage
jhonatan-lopes
import { gettext } from '../../../utils/gettext'; class BoundWidget { constructor( element, name, idForLabel, initialState, parentCapabilities, options, ) { var selector = ':is(input,select,textarea,button)[name="' + name + '"]'; // find, including element itself this.input = el...
Maybe use template literals? Also, I notice that we're changing `var`s to `const` further down, so ```suggestion const selector = `:is(input,select,textarea,button)[name="${name}"]`; ``` (there are other similar `+ name +` occurrences below)
import { gettext } from '../../../utils/gettext'; import { runInlineScripts } from '../../../utils/runInlineScripts'; class BoundWidget { constructor( element, name, idForLabel, initialState, parentCapabilities, options, ) { const selector = `:is(input,select,textarea,button)[name="${na...
@@ -10,24 +9,27 @@ class BoundWidget { parentCapabilities, options, ) { - var selector = ':input[name="' + name + '"]'; - this.input = element.find(selector).addBack(selector); // find, including element itself + var selector = ':is(input,select,textarea,button)[name="' + name + '"]';
client/src/entrypoints/admin/telepath/widgets.js
12
JavaScript
0.857
suggestion
253
37
37
false
Eliminate jQuery from telepath widget classes
11,839
wagtail/wagtail
16,097
Python
laymonage
gasman
render( placeholder, name, id, initialState, parentCapabilities, options = {}, ) { const html = this.html.replace(/__NAME__/g, name).replace(/__ID__/g, id); const idForLabel = this.idPattern.replace(/__ID__/g, id); /* write the HTML into a temp container to parse it into an ele...
Note that this would only execute inline scripts, and scripts with `src`s will be replaced with empty scripts (as the attributes are not carried over). I did something similar for the `TeleportController`, but only targeted scripts without `src` and without an explicit `type`, and retain any attributes from the orig...
boundWidgetClass = BoundWidget; render( placeholder, name, id, initialState, parentCapabilities, options = {}, ) { const html = this.html.replace(/__NAME__/g, name).replace(/__ID__/g, id); const idForLabel = this.idPattern.replace(/__ID__/g, id); /* write the HTML into a temp...
@@ -65,17 +67,31 @@ class Widget { parentCapabilities, options = {}, ) { - var html = this.html.replace(/__NAME__/g, name).replace(/__ID__/g, id); - var idForLabel = this.idPattern.replace(/__ID__/g, id); - var dom = $(html); + const html = this.html.replace(/__NAME__/g, name).replace(/__ID__/g...
client/src/entrypoints/admin/telepath/widgets.js
26
JavaScript
0.786
suggestion
479
51
51
false
Eliminate jQuery from telepath widget classes
11,839
wagtail/wagtail
16,097
Python
laymonage
gasman
} class Widget { constructor(html, idPattern) { this.html = html; this.idPattern = idPattern; } boundWidgetClass = BoundWidget; render( placeholder, name, id, initialState, parentCapabilities, options = {}, ) { const html = this.html.replace(/__NAME__/g, name).replace(/_...
I'm not familiar with how this code is used, but I just wanted to flag that this means the html string can only consist of one node in the top-level, and any other top-level nodes will be ignored. Probably OK for the widget's use case, but if multiple top-level nodes were desired, then we'd need something similar to wh...
} } class Widget { constructor(html, idPattern) { this.html = html; this.idPattern = idPattern; } boundWidgetClass = BoundWidget; render( placeholder, name, id, initialState, parentCapabilities, options = {}, ) { const html = this.html.replace(/__NAME__/g, name).replac...
@@ -65,17 +67,31 @@ class Widget { parentCapabilities, options = {}, ) { - var html = this.html.replace(/__NAME__/g, name).replace(/__ID__/g, id); - var idForLabel = this.idPattern.replace(/__ID__/g, id); - var dom = $(html); + const html = this.html.replace(/__NAME__/g, name).replace(/__ID__/g...
client/src/entrypoints/admin/telepath/widgets.js
26
JavaScript
0.5
suggestion
372
51
51
false
Eliminate jQuery from telepath widget classes
11,839
wagtail/wagtail
16,097
Python
laymonage
gasman
queryset = self.get_queryset() try: obj = self.find_object(queryset, request) if obj is None: raise self.model.DoesNotExist except self.model.DoesNotExist: raise Http404("not found") # Generate redirect url = get_object_deta...
I'm not sure which one is better: 1. retain all query parameters in `request.GET` except ones used for finding the object i.e. `html_path` in this case, or 2. only retain `fields` explicitly and disregard all other parameters In practice it doesn't really matter because I believe `fields` is the only query paramet...
def find_view(self, request): queryset = self.get_queryset() try: obj = self.find_object(queryset, request) if obj is None: raise self.model.DoesNotExist except self.model.DoesNotExist: raise Http404("not found") # Generate redi...
@@ -113,6 +113,9 @@ def find_view(self, request): ) ) + if "fields" in request.GET: + url = url + "?fields=" + request.GET["fields"]
wagtail/api/v2/views.py
26
Python
0.643
suggestion
1,000
51
51
false
Retain fields parameter when redirecting from find_view of API
12,141
wagtail/wagtail
16,097
Python
laymonage
ahosgood
if url_parts is None: # page is not routable return site_id, root_url, page_path = url_parts return Site.objects.get(id=site_id) @classmethod def get_indexed_objects(cls): content_type = ContentType.objects.get_for_model(cls) return super().get_...
Shouldn’t this have logic to account for `private_page_options`? Avoid defaulting to `public` if it’s not in the list of allowed options?
""" ``wagtail.models`` is split into submodules for maintainability. All definitions intended as public should be imported here (with 'noqa: F401' comments as required) and outside code should continue to import them from wagtail.models (e.g. ``from wagtail.models import Site``, not ``from wagtail.models.sites import S...
@@ -2227,6 +2227,10 @@ def get_indexed_instance(self): except self.specific_class.DoesNotExist: return None + def get_default_privacy_setting(self, request: HttpRequest): + """Set the default privacy setting for a page.""" + return {"type": "public"}
wagtail/models/__init__.py
26
Python
0.571
question
137
51
111
false
Add method to set default privacy option
12,278
wagtail/wagtail
16,097
Python
thibaudcolas
smark-1
and self.parent_page.has_workflow ): return self.submit_action() else: return self.save_action() def get_page_subtitle(self): return self.page_class.get_verbose_name() def get_edit_message_button(self): return messages.button( rev...
Issue: These should match the existing restriction names (`BaseViewRestriction.RESTRICTION_CHOICES`).
bool(self.request.POST.get("action-publish")) and self.parent_page_perms.can_publish_subpage() ): return self.publish_action() elif ( bool(self.request.POST.get("action-submit")) and self.parent_page.has_workflow ): return s...
@@ -182,13 +182,46 @@ def get_view_draft_message_button(self): def get_view_live_message_button(self): return messages.button(self.page.url, _("View live"), new_window=False) + def set_default_privacy_setting(self): + # privacy setting options ['public',"logged_in", "shared_password", "user_gr...
wagtail/admin/views/pages/create.py
26
Python
0.571
suggestion
101
51
51
false
Add method to set default privacy option
12,278
wagtail/wagtail
16,097
Python
RealOrangeOne
smark-1
# privacy setting options ['public',"logged_in", "shared_password", "user_groups"] default_privacy_setting = self.page.get_default_privacy_setting(self.request) if ( default_privacy_setting["type"] == "public" ): # default privacy setting is public no need to do anything ...
```suggestion raise ValueError( ```
) def get_view_live_message_button(self): return messages.button(self.page.url, _("View live"), new_window=False) def set_default_privacy_setting(self): # privacy setting options BaseViewRestriction.RESTRICTION_CHOICES default_privacy_setting = self.page.get_default_privacy_set...
@@ -182,13 +182,46 @@ def get_view_draft_message_button(self): def get_view_live_message_button(self): return messages.button(self.page.url, _("View live"), new_window=False) + def set_default_privacy_setting(self): + # privacy setting options ['public',"logged_in", "shared_password", "user_gr...
wagtail/admin/views/pages/create.py
26
Python
0.571
suggestion
49
51
51
false
Add method to set default privacy option
12,278
wagtail/wagtail
16,097
Python
RealOrangeOne
smark-1
def get_page_subtitle(self): return self.page_class.get_verbose_name() def get_edit_message_button(self): return messages.button( reverse("wagtailadmin_pages:edit", args=(self.page.id,)), _("Edit") ) def get_view_draft_message_button(self): return messages.butt...
Question: It looks like this method overrides whatever setting is currently set - is that intentional? It looks like it's currently being called with every save, rather than just initial creation, but I may be wrong.
bool(self.request.POST.get("action-submit")) and self.parent_page.has_workflow ): return self.submit_action() else: return self.save_action() def get_page_subtitle(self): return self.page_class.get_verbose_name() def get_edit_message_butt...
@@ -182,13 +182,46 @@ def get_view_draft_message_button(self): def get_view_live_message_button(self): return messages.button(self.page.url, _("View live"), new_window=False) + def set_default_privacy_setting(self):
wagtail/admin/views/pages/create.py
26
Python
0.429
bug
216
51
51
false
Add method to set default privacy option
12,278
wagtail/wagtail
16,097
Python
RealOrangeOne
smark-1
def get_context_data(self, parent_context): context = super().get_context_data(parent_context) page = self.object if page.id: context.update( { "workflow_history_url": reverse( "wagtailadmin_pages:workflow_history", arg...
Question: Should this be `self.object.get_view_restrictions().exists()`?
def get_context_data(self, parent_context): context = super().get_context_data(parent_context) page = self.object if page.id: context.update( { "workflow_history_url": reverse( "wagtailadmin_pages:workflow_history", arg...
@@ -287,6 +284,19 @@ def get_context_data(self, parent_context): "unlock_url": reverse("wagtailadmin_pages:unlock", args=(page.id,)), } ) + else: + # set is_public context for new pages based on parent page settings and default privacy setting + ...
wagtail/admin/ui/side_panels.py
26
Python
0.429
question
72
51
51
false
Add method to set default privacy option
12,278
wagtail/wagtail
16,097
Python
RealOrangeOne
smark-1
def get_page_subtitle(self): return self.page_class.get_verbose_name() def get_edit_message_button(self): return messages.button( reverse("wagtailadmin_pages:edit", args=(self.page.id,)), _("Edit") ) def get_view_draft_message_button(self): return messages.butt...
Nit: If you drop this comment onto the next line, the `if` should fit onto a single line
def get_page_subtitle(self): return self.page_class.get_verbose_name() def get_edit_message_button(self): return messages.button( reverse("wagtailadmin_pages:edit", args=(self.page.id,)), _("Edit") ) def get_view_draft_message_button(self): return messages.butt...
@@ -182,13 +188,47 @@ def get_view_draft_message_button(self): def get_view_live_message_button(self): return messages.button(self.page.url, _("View live"), new_window=False) + def set_default_privacy_setting(self): + # privacy setting options BaseViewRestriction.RESTRICTION_CHOICES + d...
wagtail/admin/views/pages/create.py
26
Python
0.429
nitpick
88
51
51
false
Add method to set default privacy option
12,278
wagtail/wagtail
16,097
Python
RealOrangeOne
smark-1
def set_default_privacy_setting(self): # privacy setting options BaseViewRestriction.RESTRICTION_CHOICES default_privacy_setting = self.page.get_default_privacy_setting(self.request) if ( default_privacy_setting["type"] == BaseViewRestriction.NONE ): # default privacy s...
Suggestion: ```suggestion groups_page_restriction.groups.set(default_privacy_setting["groups"]) ```
def set_default_privacy_setting(self): # privacy setting options BaseViewRestriction.RESTRICTION_CHOICES default_privacy_setting = self.page.get_default_privacy_setting(self.request) if default_privacy_setting["type"] == BaseViewRestriction.NONE: # default privacy setting is pub...
@@ -182,13 +188,47 @@ def get_view_draft_message_button(self): def get_view_live_message_button(self): return messages.button(self.page.url, _("View live"), new_window=False) + def set_default_privacy_setting(self): + # privacy setting options BaseViewRestriction.RESTRICTION_CHOICES + d...
wagtail/admin/views/pages/create.py
26
Python
0.714
suggestion
116
51
51
false
Add method to set default privacy option
12,278
wagtail/wagtail
16,097
Python
RealOrangeOne
smark-1