From 14d2bdc19a2f7142f58cd641fc723fa695aeb64c Mon Sep 17 00:00:00 2001 From: silverwind Date: Thu, 26 Nov 2026 13:40:23 +0000 Subject: [PATCH] refactor: replace cropperjs with @github/image-crop-element (#40530) Replace cropperjs, which was stuck on v1 because v2 was too complex to migrate to, with `@github/image-crop-element`, the cropper GitHub uses (2.3 KB vs 14.5 KB gzipped). A full selection of a square image uploads the original file so animated avatars keep working, any other selection uploads the selected square as PNG. Custom element events are now typed via `HTMLElementEventMap`, removing event casts. Avatar crop panel with the Gitea
logo Ref: https://github.com/go-gitea/gitea/pull/33827 Assisted-by: Claude Code:claude-opus-5-5 --- package.json | 2 +- pnpm-lock.yaml | 16 ++--- renovate.json5 | 4 -- templates/shared/avatar_upload_crop.tmpl | 4 +- tests/e2e/user-settings.test.ts | 26 +++++++ web_src/css/avatar.css | 4 ++ web_src/css/features/cropper.css | 6 -- web_src/css/index.css | 1 - web_src/js/features/common-page.ts | 4 +- web_src/js/features/comp/Cropper.ts | 88 ++++++++++++------------ web_src/js/features/comp/TextExpander.ts | 9 ++- web_src/js/globals.d.ts | 6 ++ 12 files changed, 97 insertions(+), 73 deletions(-) delete mode 100644 web_src/css/features/cropper.css diff --git a/package.json b/package.json index a996ee19351..7821de9a4b9 100644 --- a/package.json +++ b/package.json @@ -18,6 +18,7 @@ "@codemirror/state": "6.7.6", "@codemirror/view": "6.43.15", "@deltablot/dropzone": "7.4.4", + "@github/image-crop-element": "5.0.0", "@github/markdown-toolbar-element": "2.2.3", "@github/paste-markdown": "1.5.3", "@github/text-expander-element": "2.9.4", @@ -37,7 +38,6 @@ "codemirror-lang-elixir": "4.0.1", "colord": "2.14.0", "compare-versions": "6.1.1", - "cropperjs": "1.7.0", "dayjs": "1.11.23", "easymde": "2.21.0", "esbuild": "0.28.2", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 483984aa613..9456f4b2a65 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -211,6 +211,9 @@ importers: '@deltablot/dropzone': specifier: 7.4.4 version: 7.4.4 + '@github/image-crop-element': + specifier: 5.0.0 + version: 5.0.0 '@github/markdown-toolbar-element': specifier: 2.2.3 version: 2.2.3 @@ -268,9 +271,6 @@ importers: compare-versions: specifier: 6.1.1 version: 6.1.1 - cropperjs: - specifier: 1.7.0 - version: 1.7.0 dayjs: specifier: 1.11.23 version: 1.11.23 @@ -886,6 +886,9 @@ packages: '@github/combobox-nav@2.3.1': resolution: {integrity: sha512-gwxPzLw8XKecy1nP63i9lOBritS3bWmxl02UX6G0TwMQZbMem1BCS1tEZgYd3mkrkiDrUMWaX+DbFCuDFo3K+A==} + '@github/image-crop-element@5.0.0': + resolution: {integrity: sha512-Vgm2OwWAs1ESoib/t5sjxsAYo6YTOxxAjWDRxswX7qrqoyCejTZ3hshdo4Ep5e+Mz/GVTZC3rdMtg06dk/eT4g==} + '@github/markdown-toolbar-element@2.2.3': resolution: {integrity: sha512-AlquKGee+IWiAMYVB0xyHFZRMnu4n3X4HTvJHu79GiVJ1ojTukCWyxMlF5NMsecoLcBKsuBhx3QPv2vkE/zQ0A==} @@ -2018,9 +2021,6 @@ packages: crelt@1.0.6: resolution: {integrity: sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g==} - cropperjs@1.7.0: - resolution: {integrity: sha512-AkGnZxr7xAJBa63ObXq5ZKLkh9c8wisC+Ym8VzIDn3KZ+6qRTbBnOl2w2dFOTMzLP5IcfOpEK9PICDywNXhncg==} - cross-spawn@7.0.6: resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} engines: {node: '>= 8'} @@ -4739,6 +4739,8 @@ snapshots: '@github/combobox-nav@2.3.1': {} + '@github/image-crop-element@5.0.0': {} + '@github/markdown-toolbar-element@2.2.3': {} '@github/paste-markdown@1.5.3': {} @@ -5932,8 +5934,6 @@ snapshots: crelt@1.0.6: {} - cropperjs@1.7.0: {} - cross-spawn@7.0.6: dependencies: path-key: 3.1.1 diff --git a/renovate.json5 b/renovate.json5 index bc7d384ad1c..20857b460f1 100644 --- a/renovate.json5 +++ b/renovate.json5 @@ -70,10 +70,6 @@ "matchPackageNames": ["@mcaptcha/vanilla-glue"], "allowedVersions": "^0.1", // breaking changes in rc versions need to be handled }, - { - "matchPackageNames": ["cropperjs"], - "allowedVersions": "^1", // need to migrate to v2 but v2 is not compatible with v1 - }, { "matchPackageNames": ["tailwindcss"], "allowedVersions": "^3", // need to migrate diff --git a/templates/shared/avatar_upload_crop.tmpl b/templates/shared/avatar_upload_crop.tmpl index 4622dbcecdb..1ce53e70f51 100644 --- a/templates/shared/avatar_upload_crop.tmpl +++ b/templates/shared/avatar_upload_crop.tmpl @@ -1,8 +1,8 @@ {{- /* we do not need to set for/id here, global aria init code will add them automatically */ -}} - + {{- /* the cropper-panel must be next sibling of the input "avatar" */ -}}
{{ctx.Locale.Tr "settings.cropper_prompt"}}
-
+
diff --git a/tests/e2e/user-settings.test.ts b/tests/e2e/user-settings.test.ts index fbc84c7885b..2d280ce3eda 100644 --- a/tests/e2e/user-settings.test.ts +++ b/tests/e2e/user-settings.test.ts @@ -17,6 +17,32 @@ test('update profile biography', async ({page, request}) => { await expect(page.getByLabel('Biography')).toHaveText(''); }); +test('crop avatar before upload', async ({page, request}) => { + const username = `e2e-avatar-${randomString(8)}`; + await apiCreateUser(request, username); + await loginUser(page, username); + await page.goto('/user/settings'); + await expect(page.locator('image-crop:defined')).toBeAttached(); + await page.getByLabel('Choose new avatar').setInputFiles({ + name: 'avatar.gif', + mimeType: 'image/gif', + buffer: Buffer.from('R0lGODlhKAAUAPABAAAAAP///yH5BAAAAAAALAAAAAAoABQAAAI2hI+hy+2vkASw2jXT3S4fDmIeFYIjWW5nyq3s5b5VLD903dy46O326OsAgwydz7hD4pQ1pqwAADs=', 'base64'), + }); + const cropBox = page.locator('image-crop[loaded] .crop-box'); + await cropBox.dragTo(cropBox, {sourcePosition: {x: 100, y: 100}, targetPosition: {x: 20, y: 100}, steps: 4}); + await page.getByRole('button', {name: 'Update Avatar'}).click(); + await expect(page.getByText('Your avatar has been updated.', {exact: true})).toBeVisible(); + const avatar = await page.evaluate(async (src) => { + const image = new Image(); + image.src = src; + await image.decode(); + const context = document.createElement('canvas').getContext('2d')!; + context.drawImage(image, 0, 0); + return {width: image.naturalWidth, height: image.naturalHeight, pixels: [...context.getImageData(5, 0, 2, 1).data]}; + }, `/user/avatar/${username}/0`); + expect(avatar).toEqual({width: 20, height: 20, pixels: [0, 0, 0, 255, 255, 255, 255, 255]}); +}); + test('select and deselect all webhook events', async ({page}) => { await login(page); await page.goto('/user/settings/hooks/gitea/new'); diff --git a/web_src/css/avatar.css b/web_src/css/avatar.css index e1302e85d4f..41711aaf66b 100644 --- a/web_src/css/avatar.css +++ b/web_src/css/avatar.css @@ -121,3 +121,7 @@ img.ui.avatar { max-width: 80px; } } + +.cropper-panel image-crop { + max-width: 400px; +} diff --git a/web_src/css/features/cropper.css b/web_src/css/features/cropper.css deleted file mode 100644 index f7f81680060..00000000000 --- a/web_src/css/features/cropper.css +++ /dev/null @@ -1,6 +0,0 @@ -@import "cropperjs/dist/cropper.css"; - -.avatar-file-with-cropper + .cropper-panel .cropper-wrapper { - max-width: 400px; - max-height: 400px; -} diff --git a/web_src/css/index.css b/web_src/css/index.css index 4e69abd4e0a..0cee1e558a7 100644 --- a/web_src/css/index.css +++ b/web_src/css/index.css @@ -45,7 +45,6 @@ @import "./features/imagediff.css"; @import "./features/projects.css"; @import "./features/expander.css"; -@import "./features/cropper.css"; @import "./features/console.css"; @import "./features/captcha.css"; diff --git a/web_src/js/features/common-page.ts b/web_src/js/features/common-page.ts index 268dc6b5c41..4e84f2968d1 100644 --- a/web_src/js/features/common-page.ts +++ b/web_src/js/features/common-page.ts @@ -4,7 +4,7 @@ import {fomanticQuery} from '../modules/fomantic/base.ts'; import {initTabSwitcher} from '../modules/fomantic/tab.ts'; import {addDelegatedEventListener, queryElems} from '../utils/dom.ts'; import {registerGlobalInitFunc, registerGlobalSelectorFunc} from '../modules/observer.ts'; -import {initAvatarUploaderWithCropper} from './comp/Cropper.ts'; +import {initAvatarUploader} from './comp/Cropper.ts'; import {initCompSearchRepoBox} from './comp/SearchRepoBox.ts'; import {initRepoSwitcher} from './repo-switcher.ts'; import {initScopedWorkflowRequired} from './comp/ScopedWorkflows.ts'; @@ -101,7 +101,7 @@ export function initGlobalDropdown() { export function initGlobalComponent() { registerGlobalInitFunc('initTabSwitcher', initTabSwitcher); - registerGlobalInitFunc('initAvatarUploader', initAvatarUploaderWithCropper); + registerGlobalInitFunc('initAvatarUploader', initAvatarUploader); registerGlobalInitFunc('initSearchRepoBox', initCompSearchRepoBox); registerGlobalInitFunc('initRepoSwitcher', initRepoSwitcher); registerGlobalInitFunc('initScopedWorkflowRequired', initScopedWorkflowRequired); diff --git a/web_src/js/features/comp/Cropper.ts b/web_src/js/features/comp/Cropper.ts index a36689bfc27..dad83ac08f3 100644 --- a/web_src/js/features/comp/Cropper.ts +++ b/web_src/js/features/comp/Cropper.ts @@ -1,48 +1,48 @@ -import {showElem} from '../../utils/dom.ts'; +import {toggleElem} from '../../utils/dom.ts'; -type CropperOpts = { - container: HTMLElement, - imageSource: HTMLImageElement, - fileInput: HTMLInputElement, -}; - -async function initCompCropper({container, fileInput, imageSource}: CropperOpts) { - const {default: Cropper} = await import('cropperjs'); - let currentFileName = ''; - let currentFileLastModified = 0; - const cropper = new Cropper(imageSource, { - aspectRatio: 1, - viewMode: 2, - autoCrop: false, - crop() { - const canvas = cropper.getCroppedCanvas(); - canvas.toBlob((blob) => { - if (!blob) return; - const croppedFileName = currentFileName.replace(/\.[^.]{3,4}$/, '.png'); - const croppedFile = new File([blob], croppedFileName, {type: 'image/png', lastModified: currentFileLastModified}); - const dataTransfer = new DataTransfer(); - dataTransfer.items.add(croppedFile); - fileInput.files = dataTransfer.files; - }); - }, - }); - - fileInput.addEventListener('input', (e) => { - const files = (e.target as HTMLInputElement).files; - if (files?.length) { - currentFileName = files[0].name; - currentFileLastModified = files[0].lastModified; - const fileURL = URL.createObjectURL(files[0]); - imageSource.src = fileURL; - cropper.replace(fileURL); - showElem(container); - } - }); -} - -export async function initAvatarUploaderWithCropper(fileInput: HTMLInputElement) { +export async function initAvatarUploader(fileInput: HTMLInputElement) { const panel = fileInput.nextElementSibling as HTMLElement; if (!panel?.matches('.cropper-panel')) throw new Error('Missing cropper panel for avatar uploader'); - const imageSource = panel.querySelector('.cropper-source')!; - await initCompCropper({container: panel, fileInput, imageSource}); + await import('@github/image-crop-element'); + const cropper = panel.querySelector('image-crop')!; + const image = new Image(); + let initialWidth: number | null = null; + let crop: HTMLElementEventMap['image-crop-change']['detail'] | null = null; + let cropping = false; + + cropper.addEventListener('image-crop-change', ({detail}) => { + initialWidth ??= detail.width; + crop = detail; + }); + + fileInput.addEventListener('input', () => { + crop = initialWidth = null; + const file = fileInput.files![0]; + toggleElem(panel, Boolean(file)); + if (file) image.src = cropper.src = URL.createObjectURL(file); + }); + + const form = fileInput.form!; + form.addEventListener('submit', (e) => { + const {naturalWidth, naturalHeight} = image; + if (!crop || (naturalWidth === naturalHeight && crop.width === initialWidth)) return; // a full selection of a square image uploads the original to keep animations + e.preventDefault(); + if (cropping) return; + cropping = true; + const side = Math.min(crop.width, crop.height, naturalWidth, naturalHeight); + const x = Math.max(0, Math.min(crop.x, naturalWidth - side)); + const y = Math.max(0, Math.min(crop.y, naturalHeight - side)); + const canvas = document.createElement('canvas'); + canvas.width = canvas.height = side; + canvas.getContext('2d')!.drawImage(image, x, y, side, side, 0, 0, side, side); + canvas.toBlob((blob) => { + const file = fileInput.files![0]; + const dataTransfer = new DataTransfer(); + dataTransfer.items.add(new File([blob!], file.name.replace(/\.[^.]+$/, '.png'), {type: 'image/png', lastModified: file.lastModified})); + fileInput.files = dataTransfer.files; + crop = null; + cropping = false; + form.requestSubmit(e.submitter); + }); + }); } diff --git a/web_src/js/features/comp/TextExpander.ts b/web_src/js/features/comp/TextExpander.ts index 89a614ef757..f3847f8a508 100644 --- a/web_src/js/features/comp/TextExpander.ts +++ b/web_src/js/features/comp/TextExpander.ts @@ -6,7 +6,7 @@ import {createElementFromAttrs, createElementFromHTML} from '../../utils/dom.ts' import {getIssueColorClass, getIssueIcon} from '../issue.ts'; import {debounce} from '../../utils/func.ts'; import type TextExpanderElement from '@github/text-expander-element'; -import type {TextExpanderChangeEvent, TextExpanderResult} from '@github/text-expander-element'; +import type {TextExpanderResult} from '@github/text-expander-element'; import {ExclusiveFetch} from '../../modules/fetch.ts'; import type {Issue} from '../../types.ts'; @@ -69,7 +69,7 @@ export function initTextExpander(expander: TextExpanderElement) { }) || {matched: false}; }, 300); // to match onInputDebounce delay - expander.addEventListener('text-expander-change', (e: TextExpanderChangeEvent) => { + expander.addEventListener('text-expander-change', (e) => { if (!e.detail) return; const {key, text, provide} = e.detail; if (key === ':') { @@ -127,9 +127,8 @@ export function initTextExpander(expander: TextExpanderElement) { } }); - expander.addEventListener('text-expander-value', (event) => { - const {detail} = event as CustomEvent<{item: HTMLElement, key: string, value: string}>; - if (detail?.item) { + expander.addEventListener('text-expander-value', ({detail}) => { + if (detail.item) { // add a space after @mentions and #issue as it's likely the user wants one const suffix = ['@', '#'].includes(detail.key) ? ' ' : ''; detail.value = `${detail.item.getAttribute('data-value')}${suffix}`; diff --git a/web_src/js/globals.d.ts b/web_src/js/globals.d.ts index 5c9949794be..d9d7ec562bd 100644 --- a/web_src/js/globals.d.ts +++ b/web_src/js/globals.d.ts @@ -15,6 +15,12 @@ interface Element { _tippy: import('tippy.js').Instance; } +interface HTMLElementEventMap { + 'image-crop-change': CustomEvent<{x: number, y: number, width: number, height: number}>, + 'text-expander-change': import('@github/text-expander-element').TextExpanderChangeEvent, + 'text-expander-value': CustomEvent<{item: HTMLElement, key: string, value: string}>, +} + interface Window { config: { appUrl: string,