ronantakizawa/codereview-bench huggingface dataset:
Repository: directus/directus
File: api/src/websocket/authenticate.test.ts (TypeScript)

Code before:
			refresh_token: undefined,
		});
	});

	test('Short-circuits when authenticate filter is used', async () => {
		const TIMESTAMP = 456987;
		(getExpiresAtForToken as Mock).mockReturnValue(TIMESTAMP);

		const customAccountability = { admin: true };

		vi.spyOn(emitter, 'emitFilter').mockResolvedValue(customAccountability);

		const { accountability } = await authenticateConnection({
			type: 'auth',
			access_token: 'access_token',
		} as WebSocketAuthMessage);

		expect(accountability).toEqual(customAccountability);
	});

	test('Failure token expired', async () => {
		(getAccountabilityForToken as Mock).mockImplementation(() => {
			throw new InvalidCredentialsError();
		});

		vi.spyOn(emitter, 'emitFilter').mockResolvedValue(null);

		expect(() =>
			authenticateConnection({
				type: 'auth',
				access_token: 'expired',
			} as WebSocketAuthMessage),
		).rejects.toThrow('Authentication failed.');
	});

	test('Failure authentication failed', async () => {
		expect(() =>
			authenticateConnection({
				type: 'auth',
				access_token: '',
			} as WebSocketAuthMessage),
		).rejects.toThrow('Authentication failed.');
	});
});

describe('authenticationSuccess', () => {
	test('without uid', async () => {
		const result = authenticationSuccess();
		expect(result).toBe('{"type":"auth","status":"ok"}');
	});


Review comment (security):
~~Should this mocked value not be `createDefaultAccountability()` instead of `null`? This test now functions under admin permissions while it's supposed to test token expiry~~

Code after:
			accountability: { role: null },
			expires_at: TIMESTAMP,
			refresh_token: undefined,
		});
	});

	test('Short-circuits when authenticate filter is used', async () => {
		const TIMESTAMP = 456987;
		(getExpiresAtForToken as Mock).mockReturnValue(TIMESTAMP);

		const customAccountability = { admin: true };

		vi.mocked(emitter.emitFilter).mockResolvedValueOnce(customAccountability);

		const { accountability } = await authenticateConnection({
			type: 'auth',
			access_token: 'access_token',
		} as WebSocketAuthMessage);

		expect(accountability).toEqual(customAccountability);
	});

	test('Failure token expired', async () => {
		(getAccountabilityForToken as Mock).mockImplementation(() => {
			throw new InvalidCredentialsError();
		});

		expect(() =>
			authenticateConnection({
				type: 'auth',
				access_token: 'expired',
			} as WebSocketAuthMessage),
		).rejects.toThrow('Authentication failed.');
	});

	test('Failure authentication failed', async () => {
		expect(() =>
			authenticateConnection({
				type: 'auth',
				access_token: '',
			} as WebSocketAuthMessage),
		).rejects.toThrow('Authentication failed.');
	});
});

describe('authenticationSuccess', () => {
	test('without uid', async () => {
		const result = authenticationSuccess();
		expect(result).toBe('{"type":"auth","status":"ok"}');
	});
Repository: directus/directus
File: app/src/interfaces/input-rich-text-html/index.ts (TypeScript)

Code before:
								value: 'customLink',
								text: '$t:wysiwyg_options.link',
							},
							{
								value: 'unlink',
								text: '$t:wysiwyg_options.unlink',
							},
							{
								value: 'customImage',
								text: '$t:wysiwyg_options.image',
							},
							{
								value: 'customMedia',
								text: '$t:wysiwyg_options.media',
							},
							{
								value: 'table',
								text: '$t:wysiwyg_options.table',
							},
							{
								value: 'hr',
								text: '$t:wysiwyg_options.hr',
							},
							{
								value: 'customInlineCode',
								text: '$t:wysiwyg_options.inline_code',
							},
							{
								value: 'fullscreen',
								text: '$t:wysiwyg_options.fullscreen',
							},
							{
								value: 'visualaid',
								text: '$t:wysiwyg_options.visualaid',
							},
							{
								value: 'ltr rtl',
								text: '$t:wysiwyg_options.directionality',
							},
							{
								value: 'code',
								text: '$t:wysiwyg_options.source_code',
							},
						],
					},
				},
			},
			{
				field: 'font',
				name: '$t:font',
				type: 'string',

Review comment (suggestion):
Let’s use the existing translation.

```suggestion
								text: '$t:wysiwyg_options.codeblock',
```

Code after:
								value: 'customMedia',
								text: '$t:wysiwyg_options.media',
							},
							{
								value: 'table',
								text: '$t:wysiwyg_options.table',
							},
							{
								value: 'hr',
								text: '$t:wysiwyg_options.hr',
							},
							{
								value: 'fullscreen',
								text: '$t:wysiwyg_options.fullscreen',
							},
							{
								value: 'visualaid',
								text: '$t:wysiwyg_options.visualaid',
							},
							{
								value: 'ltr rtl',
								text: '$t:wysiwyg_options.directionality',
							},
							{
								value: 'code',
								text: '$t:wysiwyg_options.source_code',
							},
						],
					},
				},
			},
			{
				field: 'font',
				name: '$t:font',
				type: 'string',
				meta: {
					width: 'half',
					interface: 'select-dropdown',
					options: {
						choices: [
							{ text: '$t:sans_serif', value: 'sans-serif' },
							{ text: '$t:monospace', value: 'monospace' },
							{ text: '$t:serif', value: 'serif' },
						],
					},
				},
				schema: {
					default_value: 'sans-serif',
				},
			},
			{
Repository: directus/directus
File: app/src/interfaces/input-rich-text-html/usePre.ts (TypeScript)

Code before:
import { i18n } from '@/lang';
import { Ref } from 'vue';

type PreButton = {
	icon: string;
	tooltip: string;
	onAction: () => void;
	onSetup: (api: { setActive: (isActive: boolean) => void }) => () => void;
};

type UsablePre = {
	preButton: PreButton;
};

function isPre(node: Node): boolean {
	return node.nodeName === 'PRE';
}

export default function usePre(editor: Ref<any>): UsablePre {
	let keydownHandler: ((event: KeyboardEvent) => void) | null = null;

	const preButton: PreButton = {
		tooltip: 'Pre',
		icon: 'customPre',

		onAction: () => {
			// Remove all existing formatting before applying code formatting
			editor.value.execCommand('removeformat');
			editor.value.execCommand('mceToggleFormat', false, 'pre');
		},

		onSetup: (api) => {
			const updateActiveState = () => {
				const isPre = editor.value.formatter.match('pre');
				api.setActive(isPre);
			};

			updateActiveState();

			const preFormatUnbind = editor.value.formatter.formatChanged('pre', updateActiveState).unbind;

			keydownHandler = (event: KeyboardEvent) => {
				const currentNode = editor.value.selection.getNode();

				if (!isPre(currentNode)) return;

				if (event.key === 'Enter') {
					event.preventDefault();

Review comment (suggestion):
Let’s use the i18n message for the tooltip.

```suggestion
		tooltip: i18n.global.t('wysiwyg_options.pre'),
```

Code after:
import { i18n } from '@/lang';
import { Ref } from 'vue';

type PreButton = {
	text: string;
	tooltip: string;
	onAction: () => void;
	onSetup: (api: { setActive: (isActive: boolean) => void }) => () => void;
};

type UsablePre = {
	preButton: PreButton;
};

function isPre(node: Node): boolean {
	return node.nodeName === 'PRE';
}

export default function usePre(editor: Ref<any>): UsablePre {
	let keydownHandler: ((event: KeyboardEvent) => void) | null = null;

	const preButton: PreButton = {
		tooltip: i18n.global.t('wysiwyg_options.pre'),
		text: 'Pre',

		onAction: () => {
			// Remove all existing formatting before applying code formatting
			editor.value.execCommand('removeformat');
			editor.value.execCommand('mceToggleFormat', false, 'pre');
		},

		onSetup: (api) => {
			const updateActiveState = () => {
				const isPre = editor.value.formatter.match('pre');
				api.setActive(isPre);
			};

			updateActiveState();

			const preFormatUnbind = editor.value.formatter.formatChanged('pre', updateActiveState).unbind;

			keydownHandler = (event: KeyboardEvent) => {
				const currentNode = editor.value.selection.getNode();

				if (!isPre(currentNode)) return;

				if (event.key === 'Enter') {
					event.preventDefault();
Repository: directus/directus
File: app/src/interfaces/input-rich-text-html/usePre.ts (TypeScript)

Code before:
import { i18n } from '@/lang';
import { Ref } from 'vue';

type PreButton = {
	icon: string;
	tooltip: string;
	onAction: () => void;
	onSetup: (api: { setActive: (isActive: boolean) => void }) => () => void;
};

type UsablePre = {
	preButton: PreButton;
};

function isPre(node: Node): boolean {
	return node.nodeName === 'PRE';
}

export default function usePre(editor: Ref<any>): UsablePre {
	let keydownHandler: ((event: KeyboardEvent) => void) | null = null;

	const preButton: PreButton = {
		tooltip: 'Pre',
		icon: 'customPre',

		onAction: () => {
			// Remove all existing formatting before applying code formatting
			editor.value.execCommand('removeformat');
			editor.value.execCommand('mceToggleFormat', false, 'pre');
		},

		onSetup: (api) => {
			const updateActiveState = () => {
				const isPre = editor.value.formatter.match('pre');
				api.setActive(isPre);
			};

			updateActiveState();

			const preFormatUnbind = editor.value.formatter.formatChanged('pre', updateActiveState).unbind;

			keydownHandler = (event: KeyboardEvent) => {
				const currentNode = editor.value.selection.getNode();

				if (!isPre(currentNode)) return;

				if (event.key === 'Enter') {
					event.preventDefault();


Review comment (suggestion):
Let’s use the text directly instead of a svg icon.

```suggestion
		text: 'Pre',
```

Code after:
import { i18n } from '@/lang';
import { Ref } from 'vue';

type PreButton = {
	text: string;
	tooltip: string;
	onAction: () => void;
	onSetup: (api: { setActive: (isActive: boolean) => void }) => () => void;
};

type UsablePre = {
	preButton: PreButton;
};

function isPre(node: Node): boolean {
	return node.nodeName === 'PRE';
}

export default function usePre(editor: Ref<any>): UsablePre {
	let keydownHandler: ((event: KeyboardEvent) => void) | null = null;

	const preButton: PreButton = {
		tooltip: i18n.global.t('wysiwyg_options.pre'),
		text: 'Pre',

		onAction: () => {
			// Remove all existing formatting before applying code formatting
			editor.value.execCommand('removeformat');
			editor.value.execCommand('mceToggleFormat', false, 'pre');
		},

		onSetup: (api) => {
			const updateActiveState = () => {
				const isPre = editor.value.formatter.match('pre');
				api.setActive(isPre);
			};

			updateActiveState();

			const preFormatUnbind = editor.value.formatter.formatChanged('pre', updateActiveState).unbind;

			keydownHandler = (event: KeyboardEvent) => {
				const currentNode = editor.value.selection.getNode();

				if (!isPre(currentNode)) return;

				if (event.key === 'Enter') {
					event.preventDefault();
Repository: directus/directus
File: app/src/interfaces/input-rich-text-html/useInlineCode.ts (TypeScript)

Code before:
import { Ref } from 'vue';

type InlineCodeButton = {
	icon: string;
	tooltip: string;
	onAction: () => void;
	onSetup: (api: { setActive: (isActive: boolean) => void }) => () => void;
};

type UsableInlineCode = {
	inlineCodeButton: InlineCodeButton;
};

function isInlineCode(node: Node): boolean {
	// check if node is a code node, or if it has a code node as a child
	return node.nodeName === 'CODE' || (node as Element).querySelector('code') !== null;
}

export default function useInlineCode(editor: Ref<any>): UsableInlineCode {
	let keydownHandler: ((event: KeyboardEvent) => void) | null = null;

	const inlineCodeButton: InlineCodeButton = {
		tooltip: 'InlineCode',
		icon: 'code-sample',

		onAction: () => {
			editor.value.execCommand('mceToggleFormat', false, 'code');
		},

		onSetup: (api) => {
			const updateActiveState = () => {
				const isInlineCode = editor.value.formatter.match('code');

				api.setActive(isInlineCode);
			};

			updateActiveState();

			const codeFormatChangedUnbind = editor.value.formatter.formatChanged('code', updateActiveState).unbind;

			keydownHandler = (event: KeyboardEvent) => {
				const currentNode = editor.value.selection.getNode();
				if (!isInlineCode(currentNode)) return;

				if (event.key === 'Enter') {
					event.preventDefault();

					editor.value.execCommand('removeformat');

Review comment (suggestion):
Let’s use the i18n message here, otherwise the tooltip will display "InlineCode".

```suggestion
		tooltip: i18n.global.t('wysiwyg_options.codeblock'),
```

Code after:
import { Ref } from 'vue';
import { i18n } from '@/lang';

type InlineCodeButton = {
	icon: string;
	tooltip: string;
	onAction: () => void;
	onSetup: (api: { setActive: (isActive: boolean) => void }) => () => void;
};

type UsableInlineCode = {
	inlineCodeButton: InlineCodeButton;
};

function isInlineCode(node: Node): boolean {
	// check if node is a code node, or if it has a code node as a child
	return node.nodeName === 'CODE' || (node as Element).querySelector('code') !== null;
}

export default function useInlineCode(editor: Ref<any>): UsableInlineCode {
	let keydownHandler: ((event: KeyboardEvent) => void) | null = null;

	const inlineCodeButton: InlineCodeButton = {
		tooltip: i18n.global.t('wysiwyg_options.codeblock'),
		icon: 'code-sample',

		onAction: () => {
			editor.value.execCommand('mceToggleFormat', false, 'code');
		},

		onSetup: (api) => {
			const updateActiveState = () => {
				const isInlineCode = editor.value.formatter.match('code');

				api.setActive(isInlineCode);
			};

			updateActiveState();

			const codeFormatChangedUnbind = editor.value.formatter.formatChanged('code', updateActiveState).unbind;

			keydownHandler = (event: KeyboardEvent) => {
				const currentNode = editor.value.selection.getNode();
				if (!isInlineCode(currentNode)) return;

				if (event.key === 'Enter') {
					event.preventDefault();
Repository: directus/directus
File: packages/themes/src/composables/use-fonts.test.ts (TypeScript)

Code before:
import { describe, expect, it, vi } from 'vitest';
import { useFonts } from './use-fonts';

vi.mock('@directus/utils/browser', () => ({ cssVar: () => 'Inter' }));

const ThemeSchemaMock = {
	rules: {
		fonts: {
			display: {
				fontFamily: '"Roboto", "Open Sans"',
				fontWeight: '700',
			},
			sans: {
				fontFamily: 'Arial',
				fontWeight: '400',
			},
			serif: {
				fontFamily: '"Fira Mono"',
				fontWeight: '500',
			},
			monospace: {
				fontFamily: '"Lato"',
				fontWeight: '300',
			},
		},
		notAFontPath: {
			fontFamily: '"EB Garamond"',
			fontWeight: '700',
		},
	},
};

describe('useFonts', () => {
	it('should return googleFonts with correct families and weights', () => {
		const { googleFonts } = useFonts(ThemeSchemaMock as any);
		const fonts = googleFonts.value;

		expect(fonts).toContain('Roboto:wght@700');
		expect(fonts).toContain('Open+Sans:wght@700');
		expect(fonts).toContain('Lato:wght@300');
	});

	it('should not include local fonts in googleFonts', () => {
		const { googleFonts } = useFonts(ThemeSchemaMock as any);
		const fonts = googleFonts.value;
		expect(fonts.some((f) => f.startsWith('Fira+Mono'))).toBe(false);
	});

	it('should handle missing weights gracefully', () => {
		const theme = {
			rules: {

Review comment (suggestion):
This property doesn't appear to be part of the Theme type and I don't see it mentioned in the tests. Is it being used for anything?

If we don't need it, we can set the type of the ThemeSchemaMock to be a partial of the Theme type.

Code after:
import { describe, expect, it, vi } from 'vitest';
import { useFonts } from './use-fonts';

vi.mock('@directus/utils/browser', () => ({ cssVar: () => 'Inter' }));

const ThemeSchemaMock = {
	rules: {
		fonts: {
			display: {
				fontFamily: '"Roboto", "Open Sans"',
				fontWeight: '700',
			},
			sans: {
				fontFamily: 'Arial',
				fontWeight: '400',
			},
			serif: {
				fontFamily: '"Fira Mono"',
				fontWeight: '500',
			},
			monospace: {
				fontFamily: '"Lato"',
				fontWeight: '300',
			},
		},
		notAFontPath: {
			fontFamily: '"EB Garamond"',
			fontWeight: '700',
		},
	},
};

describe('useFonts', () => {
	it('should return googleFonts with correct families and weights', () => {
		const { googleFonts } = useFonts(ThemeSchemaMock);
		const fonts = googleFonts.value;

		expect(fonts).toContain('Roboto:wght@700');
		expect(fonts).toContain('Open+Sans:wght@700');
		expect(fonts).toContain('Lato:wght@300');
	});

	it('should not include local fonts in googleFonts', () => {
		const { googleFonts } = useFonts(ThemeSchemaMock);
		const fonts = googleFonts.value;
		expect(fonts.some((f) => f.startsWith('Fira+Mono'))).toBe(false);
	});

	it('should handle missing weights gracefully', () => {
		const theme = {
			rules: {
Repository: directus/directus
File: app/src/views/private/components/overlay-item.vue (Vue)

Code before:
		:icon="collectionInfo?.meta?.icon ?? undefined"
		persistent
		:apply-shortcut
		@apply="save"
		@cancel="cancel"
	>
		<template v-if="template !== null && templateData && primaryKey !== '+'" #title>
			<v-skeleton-loader v-if="loading || templateDataLoading" class="title-loader" type="text" />

			<h1 v-else class="type-title">
				<render-template :collection="templateCollection?.collection" :item="templateData" :template="template" />
			</h1>
		</template>

		<template #subtitle>
			<v-breadcrumb :items="[{ name: collectionInfo?.name, disabled: true }]" />
		</template>

		<template #actions>
			<slot name="actions" />

			<v-button
				v-tooltip.bottom="getTooltip('save', t('save'))"
				icon
				rounded
				:disabled="!isSavable || !hasEdits"
				@click="save"
			>
				<v-icon name="check" />
			</v-button>
		</template>

		<overlay-item-content
			v-model:internal-edits="internalEdits"
			v-bind="overlayItemContentProps"
			class="drawer-item-content"
		/>
	</v-drawer>

	<v-dialog
		v-else-if="overlay === 'modal'"
		v-model="overlayActive"
		persistent
		keep-behind
		:apply-shortcut
		@apply="save"
		@esc="cancel"
	>
		<v-card class="modal-card">
			<v-card-title>
				<v-icon :name="collectionInfo?.meta?.icon ?? undefined" class="modal-title-icon" />

Review comment (suggestion):
Let’s move the `hasEdits` condition to the `isSavable` computed, so we can take advantage of this improvement when using shortcuts and also when using other `overlay` types.

Code after:
		:icon="collectionInfo?.meta?.icon ?? undefined"
		persistent
		:apply-shortcut
		@apply="save"
		@cancel="cancel"
	>
		<template v-if="template !== null && templateData && primaryKey !== '+'" #title>
			<v-skeleton-loader v-if="loading || templateDataLoading" class="title-loader" type="text" />

			<h1 v-else class="type-title">
				<render-template :collection="templateCollection?.collection" :item="templateData" :template="template" />
			</h1>
		</template>

		<template #subtitle>
			<v-breadcrumb :items="[{ name: collectionInfo?.name, disabled: true }]" />
		</template>

		<template #actions>
			<slot name="actions" />

			<v-button v-tooltip.bottom="getTooltip('save', t('save'))" icon rounded :disabled="!isSavable" @click="save">
				<v-icon name="check" />
			</v-button>
		</template>

		<overlay-item-content
			v-model:internal-edits="internalEdits"
			v-bind="overlayItemContentProps"
			class="drawer-item-content"
		/>
	</v-drawer>

	<v-dialog
		v-else-if="overlay === 'modal'"
		v-model="overlayActive"
		persistent
		keep-behind
		:apply-shortcut
		@apply="save"
		@esc="cancel"
	>
		<v-card class="modal-card">
			<v-card-title>
				<v-icon :name="collectionInfo?.meta?.icon ?? undefined" class="modal-title-icon" />
				{{ title }}
			</v-card-title>

			<overlay-item-content
				v-model:internal-edits="internalEdits"
				v-bind="overlayItemContentProps"
Repository: directus/directus
File: app/src/views/private/components/drawer-collection.vue (Vue)

Code before:
		return internalSelection.value;
	},
	set(newFilters) {
		onSelect(newFilters);
	},
});

const { layoutWrapper } = useLayout(layout);

const initialSelection = ref<(string | number)[] | null>(null);

watch(
	() => internalActive.value,
	(active) => {
		if (active) {
			// Store a copy of the initial selection when the drawer opens
			initialSelection.value = Array.isArray(internalSelection.value)
				? [...internalSelection.value]
				: internalSelection.value;
		}
	},
);

const hasSelectionChanged = computed(() => {
	return !isEqual(internalSelection.value, initialSelection.value);
});

function useActiveState() {
	const localActive = ref(false);

	const internalActive = computed({
		get() {
			return props.active === undefined ? localActive.value : props.active;
		},
		set(newActive: boolean) {
			localActive.value = newActive;
			emit('update:active', newActive);
		},
	});

	return { internalActive };
}

function useSelection() {
	const localSelection = ref<(string | number)[] | null>(null);

	const internalSelection = computed({
		get() {
			if (localSelection.value === null) {
				return props.selection;
			}

Review comment (suggestion):
Let’s move these lines into the existing `useSelection` inline composable below. The contents of your watcher could be moved into the watcher on line 112. Then, the computed could be returned by `useSelection`.

Code after:
		return internalSelection.value;
	},
	set(newFilters) {
		onSelect(newFilters);
	},
});

const { layoutWrapper } = useLayout(layout);

function useActiveState() {
	const localActive = ref(false);

	const internalActive = computed({
		get() {
			return props.active === undefined ? localActive.value : props.active;
		},
		set(newActive: boolean) {
			localActive.value = newActive;
			emit('update:active', newActive);
		},
	});

	return { internalActive };
}

function useSelection() {
	const localSelection = ref<(string | number)[] | null>(null);
	const initialSelection = ref<(string | number)[] | null>(null);

	const internalSelection = computed({
		get() {
			if (localSelection.value === null) {
				return props.selection;
			}

			return localSelection.value;
		},
		set(newSelection: (string | number)[]) {
			localSelection.value = newSelection;
		},
	});

	const hasSelectionChanged = computed(() => {
		return !isEqual(internalSelection.value, initialSelection.value);
	});

	watch(
		() => props.active,
		(active) => {
			localSelection.value = null;