mirror of
https://github.com/go-gitea/gitea.git
synced 2026-11-26 10:47:04 -06:00
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:
@@ -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",
|
||||
|
||||
16
pnpm-lock.yaml
generated
16
pnpm-lock.yaml
generated
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
{{- /* we do not need to set for/id here, global aria init code will add them automatically */ -}}
|
||||
<label>{{.LabelText}}</label>
|
||||
<input class="avatar-file-with-cropper" name="avatar" type="file" accept="image/png,image/jpeg,image/gif,image/webp" data-global-init="initAvatarUploader">
|
||||
<input name="avatar" type="file" accept="image/png,image/jpeg,image/gif,image/webp" data-global-init="initAvatarUploader">
|
||||
{{- /* the cropper-panel must be next sibling of the input "avatar" */ -}}
|
||||
<div class="cropper-panel tw-hidden">
|
||||
<div class="tw-my-2">{{ctx.Locale.Tr "settings.cropper_prompt"}}</div>
|
||||
<div class="cropper-wrapper"><img class="cropper-source" alt></div>
|
||||
<image-crop tabindex="0"></image-crop>
|
||||
</div>
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -121,3 +121,7 @@ img.ui.avatar {
|
||||
max-width: 80px;
|
||||
}
|
||||
}
|
||||
|
||||
.cropper-panel image-crop {
|
||||
max-width: 400px;
|
||||
}
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
@import "cropperjs/dist/cropper.css";
|
||||
|
||||
.avatar-file-with-cropper + .cropper-panel .cropper-wrapper {
|
||||
max-width: 400px;
|
||||
max-height: 400px;
|
||||
}
|
||||
@@ -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";
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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}`;
|
||||
|
||||
6
web_src/js/globals.d.ts
vendored
6
web_src/js/globals.d.ts
vendored
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user