import { html, nothing, type TemplateResult } from 'lit'; import type { NuiType } from '../../types/nui-type.js'; import type { FileUploadItem, UploadMode } from './types.js'; export interface NuiFileUploadViewState { model: FileUploadItem[]; mode: UploadMode; multiple: boolean; accept: string; disabled: boolean; auto: boolean; maxFileSize?: number; chooseLabel: string; uploadLabel: string; cancelLabel: string; chooseIcon: string; uploadIcon: string; cancelIcon: string; customUpload: boolean; unstyled: boolean; nuiType: NuiType; fileUploadClass: string; isUploading: boolean; uploadProgress: number; dragover: boolean; } export interface FileUploadRenderHandlers { onChooseClick: () => void; onUploadClick: () => void; onCancelClick: () => void; onRemoveItem: (id: string) => void; onInputChange: (e: Event) => void; onDragOver: (e: DragEvent) => void; onDragLeave: (e: DragEvent) => void; onDrop: (e: DragEvent) => void; } export function formatBytes(bytes: number, decimals = 2): string { if (bytes === 0) return '0 Bytes'; const k = 1024; const dm = decimals < 0 ? 0 : decimals; const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return `${parseFloat((bytes / k ** i).toFixed(dm))} ${sizes[i]}`; } function renderAdvanced( state: NuiFileUploadViewState, handlers: FileUploadRenderHandlers, ): TemplateResult { const hasFiles = state.model && state.model.length > 0; const showUploadButton = hasFiles && !state.auto; const showCancelButton = hasFiles && !state.auto; return html`
${ showUploadButton ? html` ` : nothing } ${ showCancelButton ? html` ` : nothing } ${ state.isUploading ? html`
` : nothing }
${ !hasFiles ? html`
Drag and drop files here to upload.
` : html`
${state.model.map( (item) => html`
${ item.objectURL ? html` ${item.name} ` : html` ` }
${item.name} ${formatBytes(item.size)}
${item.status}
`, )}
` }
`; } function renderBasic( state: NuiFileUploadViewState, handlers: FileUploadRenderHandlers, ): TemplateResult { const hasFiles = state.model && state.model.length > 0; const fileName = hasFiles ? state.model[0].name : ''; return html`
${ hasFiles ? html` ${fileName} (${formatBytes(state.model[0].size)}) ` : nothing } ${ state.isUploading ? html` ` : nothing }
`; } export function renderFileUpload( state: NuiFileUploadViewState, handlers: FileUploadRenderHandlers, ): TemplateResult { if (state.mode === 'basic') { return renderBasic(state, handlers); } return renderAdvanced(state, handlers); }