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.

<img width="208" height="208" alt="Avatar crop panel with the Gitea
logo"
src="https://github.com/user-attachments/assets/dbdc2744-592a-45ea-91d2-356c34a0d52b">

Ref: https://github.com/go-gitea/gitea/pull/33827

Assisted-by: Claude Code:claude-opus-5-5
This commit is contained in:
silverwind
2026-11-26 13:40:23 +00:00
committed by GitHub
parent 34ef7ae9e4
commit 14d2bdc19a
12 changed files with 97 additions and 73 deletions

View File

@@ -121,3 +121,7 @@ img.ui.avatar {
max-width: 80px;
}
}
.cropper-panel image-crop {
max-width: 400px;
}

View File

@@ -1,6 +0,0 @@
@import "cropperjs/dist/cropper.css";
.avatar-file-with-cropper + .cropper-panel .cropper-wrapper {
max-width: 400px;
max-height: 400px;
}

View File

@@ -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";

View File

@@ -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);

View File

@@ -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<HTMLImageElement>('.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);
});
});
}

View File

@@ -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}`;

View File

@@ -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,