Refactor dees-input-fileupload component and styles
- Updated demo.ts to enhance layout and styling, including renaming classes and adjusting spacing. - Removed unused template rendering logic from template.ts. - Simplified index.ts by removing the export of renderFileupload. - Revamped styles in styles.ts for improved design consistency and responsiveness. - Enhanced file upload functionality with better descriptions and validation messages.
This commit is contained in:
@@ -1,15 +1,15 @@
|
||||
import { DeesContextmenu } from '../dees-contextmenu.js';
|
||||
import { DeesInputBase } from '../dees-input-base.js';
|
||||
import { demoFunc } from './demo.js';
|
||||
import { fileuploadStyles } from './styles.js';
|
||||
import { renderFileupload } from './template.js';
|
||||
import '../dees-icon.js';
|
||||
import '../dees-label.js';
|
||||
|
||||
import {
|
||||
customElement,
|
||||
type TemplateResult,
|
||||
html,
|
||||
property,
|
||||
state,
|
||||
type TemplateResult,
|
||||
} from '@design.estate/dees-element';
|
||||
|
||||
declare global {
|
||||
@@ -22,22 +22,17 @@ declare global {
|
||||
export class DeesInputFileupload extends DeesInputBase<DeesInputFileupload> {
|
||||
public static demo = demoFunc;
|
||||
|
||||
|
||||
@property({
|
||||
attribute: false,
|
||||
})
|
||||
@property({ attribute: false })
|
||||
public value: File[] = [];
|
||||
|
||||
@property()
|
||||
@state()
|
||||
public state: 'idle' | 'dragOver' | 'dropped' | 'uploading' | 'completed' = 'idle';
|
||||
|
||||
@property({ type: Boolean })
|
||||
@state()
|
||||
public isLoading: boolean = false;
|
||||
|
||||
@property({
|
||||
type: String,
|
||||
})
|
||||
public buttonText: string = 'Upload File...';
|
||||
@property({ type: String })
|
||||
public buttonText: string = 'Select files';
|
||||
|
||||
@property({ type: String })
|
||||
public accept: string = '';
|
||||
@@ -54,24 +49,258 @@ export class DeesInputFileupload extends DeesInputBase<DeesInputFileupload> {
|
||||
@property({ type: String, reflect: true })
|
||||
public validationState: 'valid' | 'invalid' | 'warn' | 'pending' = null;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
}
|
||||
public validationMessage: string = '';
|
||||
|
||||
private previewUrlMap: WeakMap<File, string> = new WeakMap();
|
||||
private dropArea: HTMLElement | null = null;
|
||||
|
||||
public static styles = fileuploadStyles;
|
||||
|
||||
public render(): TemplateResult {
|
||||
return renderFileupload(this);
|
||||
const acceptedSummary = this.getAcceptedSummary();
|
||||
const metaEntries: string[] = [
|
||||
this.multiple ? 'Multiple files supported' : 'Single file only',
|
||||
this.maxSize > 0 ? `Max ${this.formatFileSize(this.maxSize)}` : 'No size limit',
|
||||
];
|
||||
|
||||
if (acceptedSummary) {
|
||||
metaEntries.push(`Accepts ${acceptedSummary}`);
|
||||
}
|
||||
|
||||
return html`
|
||||
<div class="input-wrapper">
|
||||
<dees-label
|
||||
.label=${this.label}
|
||||
.description=${this.description}
|
||||
.required=${this.required}
|
||||
></dees-label>
|
||||
<div
|
||||
class="dropzone ${this.state === 'dragOver' ? 'dropzone--active' : ''} ${this.disabled ? 'dropzone--disabled' : ''}"
|
||||
role="button"
|
||||
tabindex=${this.disabled ? -1 : 0}
|
||||
aria-disabled=${this.disabled}
|
||||
aria-label=${`Select files${acceptedSummary ? ` (${acceptedSummary})` : ''}`}
|
||||
@click=${this.handleDropzoneClick}
|
||||
@keydown=${this.handleDropzoneKeydown}
|
||||
>
|
||||
<input
|
||||
class="file-input"
|
||||
style="position: absolute; opacity: 0; pointer-events: none; width: 1px; height: 1px; top: 0; left: 0; overflow: hidden;"
|
||||
type="file"
|
||||
?multiple=${this.multiple}
|
||||
accept=${this.accept || ''}
|
||||
?disabled=${this.disabled}
|
||||
@change=${this.handleFileInputChange}
|
||||
tabindex="-1"
|
||||
/>
|
||||
<div class="dropzone__body">
|
||||
<div class="dropzone__icon">
|
||||
${this.isLoading
|
||||
? html`<span class="dropzone__loader" aria-hidden="true"></span>`
|
||||
: html`<dees-icon icon="lucide:FolderOpen"></dees-icon>`}
|
||||
</div>
|
||||
<div class="dropzone__content">
|
||||
<span class="dropzone__headline">${this.buttonText || 'Select files'}</span>
|
||||
<span class="dropzone__subline">
|
||||
Drag and drop files here or
|
||||
<button
|
||||
type="button"
|
||||
class="dropzone__browse"
|
||||
@click=${this.handleBrowseClick}
|
||||
?disabled=${this.disabled}
|
||||
>
|
||||
browse
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="dropzone__meta">
|
||||
${metaEntries.map((entry) => html`<span>${entry}</span>`)}
|
||||
</div>
|
||||
</div>
|
||||
${this.renderFileList()}
|
||||
${this.validationMessage
|
||||
? html`<div class="validation-message" aria-live="polite">${this.validationMessage}</div>`
|
||||
: html``}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
public validationMessage: string = '';
|
||||
private renderFileList(): TemplateResult {
|
||||
if (this.value.length === 0) {
|
||||
return html`
|
||||
<div class="file-empty">
|
||||
<div class="file-empty__title">No files selected</div>
|
||||
<div class="file-empty__hint">
|
||||
Selected files will be listed here
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
return html`
|
||||
<div class="file-list">
|
||||
<div class="file-list__header">
|
||||
<span>${this.value.length} file${this.value.length === 1 ? '' : 's'} selected</span>
|
||||
${this.value.length > 0
|
||||
? html`<button type="button" class="file-list__clear" @click=${this.handleClearAll}>Clear ${this.value.length > 1 ? 'all' : ''}</button>`
|
||||
: html``}
|
||||
</div>
|
||||
<div class="file-list__items">
|
||||
${this.value.map((file) => this.renderFileRow(file))}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
private renderFileRow(file: File): TemplateResult {
|
||||
const fileType = this.getFileType(file);
|
||||
const previewUrl = this.canShowPreview(file) ? this.getPreviewUrl(file) : null;
|
||||
|
||||
return html`
|
||||
<div class="file-row ${fileType}-file">
|
||||
<div class="file-thumb" aria-hidden="true">
|
||||
${previewUrl
|
||||
? html`<img class="thumb-image" src=${previewUrl} alt=${`Preview of ${file.name}`}>`
|
||||
: html`<dees-icon icon=${this.getFileIcon(file)}></dees-icon>`}
|
||||
</div>
|
||||
<div class="file-meta">
|
||||
<div class="file-name" title=${file.name}>${file.name}</div>
|
||||
<div class="file-details">
|
||||
<span class="file-size">${this.formatFileSize(file.size)}</span>
|
||||
${fileType !== 'file' ? html`<span class="file-type">${fileType}</span>` : html``}
|
||||
</div>
|
||||
</div>
|
||||
<div class="file-actions">
|
||||
<button
|
||||
type="button"
|
||||
class="remove-button"
|
||||
@click=${() => this.removeFile(file)}
|
||||
aria-label=${`Remove ${file.name}`}
|
||||
>
|
||||
<dees-icon icon="lucide:X"></dees-icon>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
private handleFileInputChange = async (event: Event) => {
|
||||
this.isLoading = false;
|
||||
const target = event.target as HTMLInputElement;
|
||||
const files = Array.from(target.files ?? []);
|
||||
if (files.length > 0) {
|
||||
await this.addFiles(files);
|
||||
}
|
||||
target.value = '';
|
||||
};
|
||||
|
||||
private handleDropzoneClick = (event: MouseEvent) => {
|
||||
if (this.disabled) {
|
||||
return;
|
||||
}
|
||||
// Don't prevent default - let the click bubble
|
||||
if ((event.target as HTMLElement).closest('.dropzone__browse')) {
|
||||
return;
|
||||
}
|
||||
this.openFileSelector();
|
||||
};
|
||||
|
||||
private handleBrowseClick = (event: MouseEvent) => {
|
||||
if (this.disabled) {
|
||||
return;
|
||||
}
|
||||
event.stopPropagation(); // Stop propagation to prevent double trigger
|
||||
this.openFileSelector();
|
||||
};
|
||||
|
||||
private handleDropzoneKeydown = (event: KeyboardEvent) => {
|
||||
if (this.disabled) {
|
||||
return;
|
||||
}
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault();
|
||||
this.openFileSelector();
|
||||
}
|
||||
};
|
||||
|
||||
private handleClearAll = (event: MouseEvent) => {
|
||||
event.preventDefault();
|
||||
this.clearAll();
|
||||
};
|
||||
|
||||
private handleDragEvent = async (event: DragEvent) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
|
||||
if (this.disabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === 'dragenter' || event.type === 'dragover') {
|
||||
if (event.dataTransfer) {
|
||||
event.dataTransfer.dropEffect = 'copy';
|
||||
}
|
||||
this.state = 'dragOver';
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === 'dragleave') {
|
||||
if (!this.dropArea) {
|
||||
this.state = 'idle';
|
||||
return;
|
||||
}
|
||||
const rect = this.dropArea.getBoundingClientRect();
|
||||
const { clientX = 0, clientY = 0 } = event;
|
||||
if (clientX <= rect.left || clientX >= rect.right || clientY <= rect.top || clientY >= rect.bottom) {
|
||||
this.state = 'idle';
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === 'drop') {
|
||||
this.state = 'idle';
|
||||
const files = Array.from(event.dataTransfer?.files ?? []);
|
||||
if (files.length > 0) {
|
||||
await this.addFiles(files);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private attachDropListeners(): void {
|
||||
if (!this.dropArea) {
|
||||
return;
|
||||
}
|
||||
['dragenter', 'dragover', 'dragleave', 'drop'].forEach((eventName) => {
|
||||
this.dropArea!.addEventListener(eventName, this.handleDragEvent);
|
||||
});
|
||||
}
|
||||
|
||||
private detachDropListeners(): void {
|
||||
if (!this.dropArea) {
|
||||
return;
|
||||
}
|
||||
['dragenter', 'dragover', 'dragleave', 'drop'].forEach((eventName) => {
|
||||
this.dropArea!.removeEventListener(eventName, this.handleDragEvent);
|
||||
});
|
||||
}
|
||||
|
||||
private rebindInteractiveElements(): void {
|
||||
const newDropArea = this.shadowRoot?.querySelector('.dropzone') as HTMLElement | null;
|
||||
|
||||
if (newDropArea !== this.dropArea) {
|
||||
this.detachDropListeners();
|
||||
this.dropArea = newDropArea;
|
||||
this.attachDropListeners();
|
||||
}
|
||||
}
|
||||
|
||||
// Utility methods
|
||||
public formatFileSize(bytes: number): string {
|
||||
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
|
||||
const units = ['Bytes', 'KB', 'MB', 'GB'];
|
||||
if (bytes === 0) return '0 Bytes';
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(1024));
|
||||
return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i];
|
||||
const exponent = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), units.length - 1);
|
||||
const size = bytes / Math.pow(1024, exponent);
|
||||
return `${Math.round(size * 100) / 100} ${units[exponent]}`;
|
||||
}
|
||||
|
||||
public getFileType(file: File): string {
|
||||
@@ -88,176 +317,257 @@ export class DeesInputFileupload extends DeesInputBase<DeesInputFileupload> {
|
||||
}
|
||||
|
||||
public getFileIcon(file: File): string {
|
||||
const type = this.getFileType(file);
|
||||
const iconMap = {
|
||||
'image': 'lucide:image',
|
||||
'pdf': 'lucide:file-text',
|
||||
'doc': 'lucide:file-text',
|
||||
'spreadsheet': 'lucide:table',
|
||||
'presentation': 'lucide:presentation',
|
||||
'video': 'lucide:video',
|
||||
'audio': 'lucide:music',
|
||||
'archive': 'lucide:archive',
|
||||
'file': 'lucide:file'
|
||||
const fileType = this.getFileType(file);
|
||||
const iconMap: Record<string, string> = {
|
||||
image: 'lucide:FileImage',
|
||||
pdf: 'lucide:FileText',
|
||||
doc: 'lucide:FileText',
|
||||
spreadsheet: 'lucide:FileSpreadsheet',
|
||||
presentation: 'lucide:FileBarChart',
|
||||
video: 'lucide:FileVideo',
|
||||
audio: 'lucide:FileAudio',
|
||||
archive: 'lucide:FileArchive',
|
||||
file: 'lucide:File',
|
||||
};
|
||||
return iconMap[type] || 'lucide:file';
|
||||
return iconMap[fileType] ?? 'lucide:File';
|
||||
}
|
||||
|
||||
public canShowPreview(file: File): boolean {
|
||||
return file.type.startsWith('image/') && file.size < 5 * 1024 * 1024; // 5MB limit for previews
|
||||
return file.type.startsWith('image/') && file.size < 5 * 1024 * 1024;
|
||||
}
|
||||
|
||||
private validateFile(file: File): boolean {
|
||||
// Check file size
|
||||
if (this.maxSize > 0 && file.size > this.maxSize) {
|
||||
this.validationMessage = `File "${file.name}" exceeds maximum size of ${this.formatFileSize(this.maxSize)}`;
|
||||
this.validationMessage = `File "${file.name}" exceeds the maximum size of ${this.formatFileSize(this.maxSize)}`;
|
||||
this.validationState = 'invalid';
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check file type
|
||||
if (this.accept) {
|
||||
const acceptedTypes = this.accept.split(',').map(s => s.trim());
|
||||
let isAccepted = false;
|
||||
|
||||
for (const acceptType of acceptedTypes) {
|
||||
if (acceptType.startsWith('.')) {
|
||||
// Extension check
|
||||
if (file.name.toLowerCase().endsWith(acceptType.toLowerCase())) {
|
||||
const acceptedTypes = this.accept
|
||||
.split(',')
|
||||
.map((entry) => entry.trim())
|
||||
.filter((entry) => entry.length > 0);
|
||||
|
||||
if (acceptedTypes.length > 0) {
|
||||
let isAccepted = false;
|
||||
for (const acceptType of acceptedTypes) {
|
||||
if (acceptType.startsWith('.')) {
|
||||
if (file.name.toLowerCase().endsWith(acceptType.toLowerCase())) {
|
||||
isAccepted = true;
|
||||
break;
|
||||
}
|
||||
} else if (acceptType.endsWith('/*')) {
|
||||
const prefix = acceptType.slice(0, -2);
|
||||
if (file.type.startsWith(prefix)) {
|
||||
isAccepted = true;
|
||||
break;
|
||||
}
|
||||
} else if (file.type === acceptType) {
|
||||
isAccepted = true;
|
||||
break;
|
||||
}
|
||||
} else if (acceptType.endsWith('/*')) {
|
||||
// MIME type wildcard check
|
||||
const mimePrefix = acceptType.slice(0, -2);
|
||||
if (file.type.startsWith(mimePrefix)) {
|
||||
isAccepted = true;
|
||||
break;
|
||||
}
|
||||
} else if (file.type === acceptType) {
|
||||
// Exact MIME type check
|
||||
isAccepted = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!isAccepted) {
|
||||
this.validationMessage = `File type not accepted. Please upload: ${this.accept}`;
|
||||
this.validationState = 'invalid';
|
||||
return false;
|
||||
|
||||
if (!isAccepted) {
|
||||
this.validationMessage = `File type not accepted. Allowed: ${acceptedTypes.join(', ')}`;
|
||||
this.validationState = 'invalid';
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private getPreviewUrl(file: File): string {
|
||||
let url = this.previewUrlMap.get(file);
|
||||
if (!url) {
|
||||
url = URL.createObjectURL(file);
|
||||
this.previewUrlMap.set(file, url);
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
private releasePreview(file: File): void {
|
||||
const url = this.previewUrlMap.get(file);
|
||||
if (url) {
|
||||
URL.revokeObjectURL(url);
|
||||
this.previewUrlMap.delete(file);
|
||||
}
|
||||
}
|
||||
|
||||
private getAcceptedSummary(): string | null {
|
||||
if (!this.accept) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const formatted = Array.from(
|
||||
new Set(
|
||||
this.accept
|
||||
.split(',')
|
||||
.map((token) => token.trim())
|
||||
.filter((token) => token.length > 0)
|
||||
.map((token) => this.formatAcceptToken(token))
|
||||
)
|
||||
).filter(Boolean);
|
||||
|
||||
if (formatted.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (formatted.length === 1) {
|
||||
return formatted[0];
|
||||
}
|
||||
|
||||
if (formatted.length === 2) {
|
||||
return `${formatted[0]}, ${formatted[1]}`;
|
||||
}
|
||||
|
||||
return `${formatted.slice(0, 2).join(', ')}…`;
|
||||
}
|
||||
|
||||
private formatAcceptToken(token: string): string {
|
||||
if (token === '*/*') {
|
||||
return 'All files';
|
||||
}
|
||||
|
||||
if (token.endsWith('/*')) {
|
||||
const family = token.split('/')[0];
|
||||
if (!family) {
|
||||
return 'All files';
|
||||
}
|
||||
return `${family.charAt(0).toUpperCase()}${family.slice(1)} files`;
|
||||
}
|
||||
|
||||
if (token.startsWith('.')) {
|
||||
return token.slice(1).toUpperCase();
|
||||
}
|
||||
|
||||
if (token.includes('pdf')) return 'PDF';
|
||||
if (token.includes('zip')) return 'ZIP';
|
||||
if (token.includes('json')) return 'JSON';
|
||||
if (token.includes('msword')) return 'DOC';
|
||||
if (token.includes('wordprocessingml')) return 'DOCX';
|
||||
if (token.includes('excel')) return 'XLS';
|
||||
if (token.includes('presentation')) return 'PPT';
|
||||
|
||||
const segments = token.split('/');
|
||||
const lastSegment = segments.pop() ?? token;
|
||||
return lastSegment.toUpperCase();
|
||||
}
|
||||
|
||||
private attachLifecycleListeners(): void {
|
||||
this.rebindInteractiveElements();
|
||||
}
|
||||
|
||||
public firstUpdated(changedProperties: Map<string, unknown>) {
|
||||
super.firstUpdated(changedProperties);
|
||||
this.attachLifecycleListeners();
|
||||
}
|
||||
|
||||
public updated(changedProperties: Map<string, unknown>) {
|
||||
super.updated(changedProperties);
|
||||
if (changedProperties.has('value')) {
|
||||
void this.validate();
|
||||
}
|
||||
this.rebindInteractiveElements();
|
||||
}
|
||||
|
||||
public async disconnectedCallback(): Promise<void> {
|
||||
this.detachDropListeners();
|
||||
this.value.forEach((file) => this.releasePreview(file));
|
||||
this.previewUrlMap = new WeakMap();
|
||||
await super.disconnectedCallback();
|
||||
}
|
||||
|
||||
public async openFileSelector() {
|
||||
if (this.disabled || this.isLoading) return;
|
||||
|
||||
// Set loading state
|
||||
if (this.disabled || this.isLoading) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.isLoading = true;
|
||||
|
||||
const inputFile: HTMLInputElement = this.shadowRoot.querySelector('input[type="file"]');
|
||||
|
||||
// Set up a focus handler to detect when the dialog is closed without selection
|
||||
|
||||
// Ensure we have the latest reference to the file input
|
||||
const inputFile = this.shadowRoot?.querySelector('.file-input') as HTMLInputElement | null;
|
||||
|
||||
if (!inputFile) {
|
||||
this.isLoading = false;
|
||||
return;
|
||||
}
|
||||
|
||||
const handleFocus = () => {
|
||||
setTimeout(() => {
|
||||
// Check if no file was selected
|
||||
if (!inputFile.files || inputFile.files.length === 0) {
|
||||
this.isLoading = false;
|
||||
}
|
||||
window.removeEventListener('focus', handleFocus);
|
||||
}, 300);
|
||||
};
|
||||
|
||||
|
||||
window.addEventListener('focus', handleFocus);
|
||||
|
||||
// Click the input to open file selector
|
||||
inputFile.click();
|
||||
}
|
||||
|
||||
public removeFile(file: File) {
|
||||
const index = this.value.indexOf(file);
|
||||
if (index > -1) {
|
||||
this.releasePreview(file);
|
||||
this.value.splice(index, 1);
|
||||
this.requestUpdate();
|
||||
this.validate();
|
||||
this.requestUpdate('value');
|
||||
void this.validate();
|
||||
this.changeSubject.next(this);
|
||||
}
|
||||
}
|
||||
|
||||
public clearAll() {
|
||||
const existingFiles = [...this.value];
|
||||
this.value = [];
|
||||
this.requestUpdate();
|
||||
this.validate();
|
||||
existingFiles.forEach((file) => this.releasePreview(file));
|
||||
this.requestUpdate('value');
|
||||
void this.validate();
|
||||
this.changeSubject.next(this);
|
||||
this.buttonText = 'Select files';
|
||||
}
|
||||
|
||||
public async updateValue(eventArg: Event) {
|
||||
const target: any = eventArg.target;
|
||||
this.value = target.value;
|
||||
const target = eventArg.target as HTMLInputElement;
|
||||
this.value = Array.from(target.files ?? []);
|
||||
this.changeSubject.next(this);
|
||||
}
|
||||
|
||||
public firstUpdated(_changedProperties: Map<string | number | symbol, unknown>) {
|
||||
super.firstUpdated(_changedProperties);
|
||||
const inputFile: HTMLInputElement = this.shadowRoot.querySelector('input[type="file"]');
|
||||
inputFile.addEventListener('change', async (event: Event) => {
|
||||
const target = event.target as HTMLInputElement;
|
||||
const newFiles = Array.from(target.files);
|
||||
|
||||
// Always reset loading state when file dialog interaction completes
|
||||
this.isLoading = false;
|
||||
|
||||
await this.addFiles(newFiles);
|
||||
// Reset the input value to allow selecting the same file again if needed
|
||||
target.value = '';
|
||||
});
|
||||
public setValue(value: File[]): void {
|
||||
this.value.forEach((file) => this.releasePreview(file));
|
||||
this.value = value;
|
||||
if (value.length > 0) {
|
||||
this.buttonText = this.multiple ? 'Add more files' : 'Replace file';
|
||||
} else {
|
||||
this.buttonText = 'Select files';
|
||||
}
|
||||
this.requestUpdate('value');
|
||||
void this.validate();
|
||||
}
|
||||
|
||||
// Handle drag and drop
|
||||
const dropArea = this.shadowRoot.querySelector('.maincontainer');
|
||||
const handlerFunction = async (eventArg: DragEvent) => {
|
||||
eventArg.preventDefault();
|
||||
eventArg.stopPropagation();
|
||||
|
||||
switch (eventArg.type) {
|
||||
case 'dragenter':
|
||||
case 'dragover':
|
||||
this.state = 'dragOver';
|
||||
break;
|
||||
case 'dragleave':
|
||||
// Check if we're actually leaving the drop area
|
||||
const rect = dropArea.getBoundingClientRect();
|
||||
const x = eventArg.clientX;
|
||||
const y = eventArg.clientY;
|
||||
if (x <= rect.left || x >= rect.right || y <= rect.top || y >= rect.bottom) {
|
||||
this.state = 'idle';
|
||||
}
|
||||
break;
|
||||
case 'drop':
|
||||
this.state = 'idle';
|
||||
const files = Array.from(eventArg.dataTransfer.files);
|
||||
await this.addFiles(files);
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
dropArea.addEventListener('dragenter', handlerFunction, false);
|
||||
dropArea.addEventListener('dragleave', handlerFunction, false);
|
||||
dropArea.addEventListener('dragover', handlerFunction, false);
|
||||
dropArea.addEventListener('drop', handlerFunction, false);
|
||||
public getValue(): File[] {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
private async addFiles(files: File[]) {
|
||||
const filesToAdd: File[] = [];
|
||||
|
||||
|
||||
for (const file of files) {
|
||||
if (this.validateFile(file)) {
|
||||
filesToAdd.push(file);
|
||||
}
|
||||
}
|
||||
|
||||
if (filesToAdd.length === 0) return;
|
||||
if (filesToAdd.length === 0) {
|
||||
this.isLoading = false;
|
||||
return;
|
||||
}
|
||||
|
||||
// Check max files limit
|
||||
if (this.maxFiles > 0) {
|
||||
const totalFiles = this.value.length + filesToAdd.length;
|
||||
if (totalFiles > this.maxFiles) {
|
||||
@@ -265,6 +575,7 @@ export class DeesInputFileupload extends DeesInputBase<DeesInputFileupload> {
|
||||
if (allowedCount <= 0) {
|
||||
this.validationMessage = `Maximum ${this.maxFiles} files allowed`;
|
||||
this.validationState = 'invalid';
|
||||
this.isLoading = false;
|
||||
return;
|
||||
}
|
||||
filesToAdd.splice(allowedCount);
|
||||
@@ -273,62 +584,43 @@ export class DeesInputFileupload extends DeesInputBase<DeesInputFileupload> {
|
||||
}
|
||||
}
|
||||
|
||||
// Add files
|
||||
if (!this.multiple && filesToAdd.length > 0) {
|
||||
this.value.forEach((file) => this.releasePreview(file));
|
||||
this.value = [filesToAdd[0]];
|
||||
} else {
|
||||
this.value.push(...filesToAdd);
|
||||
}
|
||||
|
||||
this.requestUpdate();
|
||||
this.validate();
|
||||
this.validationMessage = '';
|
||||
this.validationState = null;
|
||||
this.requestUpdate('value');
|
||||
await this.validate();
|
||||
this.changeSubject.next(this);
|
||||
|
||||
// Update button text
|
||||
this.isLoading = false;
|
||||
|
||||
if (this.value.length > 0) {
|
||||
this.buttonText = this.multiple ? 'Add more files' : 'Replace file';
|
||||
} else {
|
||||
this.buttonText = 'Select files';
|
||||
}
|
||||
}
|
||||
|
||||
public async validate(): Promise<boolean> {
|
||||
this.validationMessage = '';
|
||||
|
||||
|
||||
if (this.required && this.value.length === 0) {
|
||||
this.validationState = 'invalid';
|
||||
this.validationMessage = 'Please select at least one file';
|
||||
return false;
|
||||
}
|
||||
|
||||
// Validate all files
|
||||
|
||||
for (const file of this.value) {
|
||||
if (!this.validateFile(file)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
this.validationState = 'valid';
|
||||
|
||||
this.validationState = this.value.length > 0 ? 'valid' : null;
|
||||
return true;
|
||||
}
|
||||
|
||||
public getValue(): File[] {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
public setValue(value: File[]): void {
|
||||
this.value = value;
|
||||
this.requestUpdate();
|
||||
if (value.length > 0) {
|
||||
this.buttonText = this.multiple ? 'Add more files' : 'Replace file';
|
||||
} else {
|
||||
this.buttonText = 'Upload File...';
|
||||
}
|
||||
}
|
||||
|
||||
public updated(changedProperties: Map<string, any>) {
|
||||
super.updated(changedProperties);
|
||||
|
||||
if (changedProperties.has('value')) {
|
||||
this.validate();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user