Skip to content

devex: Create and document file selection components #2654

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Jun 23, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
241 changes: 241 additions & 0 deletions frontend/src/components/ui/file-input.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,241 @@
import { localized } from "@lit/localize";
import clsx from "clsx";
import { html, nothing, type PropertyValues } from "lit";
import { customElement, property, query, state } from "lit/decorators.js";
import { ifDefined } from "lit/directives/if-defined.js";
import { repeat } from "lit/directives/repeat.js";
import { without } from "lodash/fp";

import type {
BtrixFileChangeEvent,
BtrixFileRemoveEvent,
} from "./file-list/events";

import { TailwindElement } from "@/classes/TailwindElement";
import { FormControl } from "@/mixins/FormControl";
import { tw } from "@/utils/tailwind";

import "@/components/ui/file-list";

const droppingClass = tw`bg-slate-100`;

/**
* Allow attaching one or more files.
*
* @fires btrix-change
* @fires btrix-remove
*/
@customElement("btrix-file-input")
@localized()
export class FileInput extends FormControl(TailwindElement) {
/**
* Form control name, if used as a form control
*/
@property({ type: String })
name?: string;

/**
* Form control label, if used as a form control
*/
@property({ type: String })
label?: string;

/**
* Specify which file types are allowed
*/
@property({ type: String })
accept?: HTMLInputElement["accept"];

/**
* Enable selecting more than one file
*/
@property({ type: Boolean })
multiple?: HTMLInputElement["multiple"];

/**
* Enable dragging files into drop zone
*/
@property({ type: Boolean })
drop = false;

@state()
private files: File[] = [];

@query("#dropzone")
private readonly dropzone?: HTMLElement | null;

@query("input[type='file']")
private readonly input?: HTMLInputElement | null;

formResetCallback() {
this.files = [];

if (this.input) {
this.input.value = "";
}
}

protected willUpdate(changedProperties: PropertyValues): void {
if (changedProperties.has("files")) {
this.syncFormValue();
}
}

private syncFormValue() {
const formControlName = this.name;

if (!formControlName) return;

// `ElementInternals["setFormValue"]` doesn't support `FileList` yet,
// construct `FormData` instead
const formData = new FormData();

this.files.forEach((file) => {
formData.append(formControlName, file);
});

this.setFormValue(formData);
}

render() {
return html`
${this.label
? html`<label for="fileInput" class="form-label">${this.label}</label>`
: nothing}
${this.files.length ? this.renderFiles() : this.renderInput()}
`;
}

private readonly renderInput = () => {
return html`
<div
id="dropzone"
class=${clsx(
this.drop
? tw`flex size-full cursor-pointer items-center justify-center rounded p-6 text-center outline-dashed outline-1 -outline-offset-1 outline-neutral-400 transition-all hover:bg-slate-50 hover:outline-primary-400`
: tw`size-max`,
)}
@drop=${this.drop ? this.onDrop : undefined}
@dragover=${this.drop ? this.onDragover : undefined}
@dragenter=${this.drop
? () => this.dropzone?.classList.add(droppingClass)
: undefined}
@dragleave=${this.drop
? () => this.dropzone?.classList.remove(droppingClass)
: undefined}
@click=${() => this.input?.click()}
role="button"
dropzone="copy"
aria-dropeffect="copy"
>
<input
id="fileInput"
class="sr-only"
type="file"
accept=${ifDefined(this.accept)}
?multiple=${this.multiple}
@change=${() => {
const files = this.input?.files;

if (files) {
void this.handleChange(files);
}
}}
/>
<div class="relative z-10">
<slot></slot>
</div>
</div>
`;
};

private readonly renderFiles = () => {
return html`
<btrix-file-list
@btrix-remove=${(e: BtrixFileRemoveEvent) => {
this.files = without([e.detail.item])(this.files);
}}
>
${repeat(
this.files,
(file) => file.name,
(file) => html`
<btrix-file-list-item .file=${file}></btrix-file-list-item>
`,
)}
</btrix-file-list>
`;
};

private readonly onDrop = (e: DragEvent) => {
e.preventDefault();

this.dropzone?.classList.remove(droppingClass);

const files = e.dataTransfer?.files;

if (files) {
const list = new DataTransfer();

if (this.multiple) {
[...files].forEach((file) => {
if (this.valid(file)) {
list.items.add(file);
}
});
} else {
const file = files[0];

if (this.valid(file)) {
list.items.add(file);
}
}

if (list.items.length) {
void this.handleChange(list.files);
} else {
console.debug("none valid:", files);
}
} else {
console.debug("no files dropped");
}
};

private readonly onDragover = (e: DragEvent) => {
e.preventDefault();

if (e.dataTransfer) {
this.dropzone?.classList.add(droppingClass);
e.dataTransfer.dropEffect = "copy";
}
};

/**
* @TODO More complex validation based on `accept`
*/
private valid(file: File) {
if (!this.accept) return true;

return this.accept.split(",").some((accept) => {
if (accept.startsWith(".")) {
return file.name.endsWith(accept.trim());
}

return new RegExp(accept.trim().replace("*", ".*")).test(file.type);
});
}

private async handleChange(fileList: FileList) {
this.files = [...fileList];

await this.updateComplete;

this.dispatchEvent(
new CustomEvent<BtrixFileChangeEvent["detail"]>("btrix-change", {
detail: { value: this.files },
composed: true,
bubbles: true,
}),
);
}
}
5 changes: 5 additions & 0 deletions frontend/src/components/ui/file-list/events.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import type { BtrixChangeEvent } from "@/events/btrix-change";
import type { BtrixRemoveEvent } from "@/events/btrix-remove";

export type BtrixFileRemoveEvent = BtrixRemoveEvent<File>;
export type BtrixFileChangeEvent = BtrixChangeEvent<File[]>;
Original file line number Diff line number Diff line change
@@ -1,26 +1,19 @@
import { localized, msg } from "@lit/localize";
import { css, html } from "lit";
import {
customElement,
property,
queryAssignedElements,
} from "lit/decorators.js";
import { customElement, property } from "lit/decorators.js";

import type { BtrixFileRemoveEvent } from "./events";

import { BtrixElement } from "@/classes/BtrixElement";
import { TailwindElement } from "@/classes/TailwindElement";
import { LocalizeController } from "@/controllers/localize";
import { truncate } from "@/utils/css";

type FileRemoveDetail = {
file: File;
};
export type FileRemoveEvent = CustomEvent<FileRemoveDetail>;

/**
* @event on-remove FileRemoveEvent
* @event btrix-remove
*/
@customElement("btrix-file-list-item")
@localized()
export class FileListItem extends BtrixElement {
export class FileListItem extends TailwindElement {
static styles = [
truncate,
css`
Expand Down Expand Up @@ -75,6 +68,8 @@ export class FileListItem extends BtrixElement {
@property({ type: Boolean })
progressIndeterminate?: boolean;

readonly localize = new LocalizeController(this);

render() {
if (!this.file) return;
return html`<div class="item">
Expand Down Expand Up @@ -117,50 +112,13 @@ export class FileListItem extends BtrixElement {
if (!this.file) return;
await this.updateComplete;
this.dispatchEvent(
new CustomEvent<FileRemoveDetail>("on-remove", {
new CustomEvent<BtrixFileRemoveEvent["detail"]>("btrix-remove", {
detail: {
file: this.file,
item: this.file,
},
composed: true,
bubbles: true,
}),
);
};
}

@customElement("btrix-file-list")
export class FileList extends TailwindElement {
static styles = [
css`
::slotted(btrix-file-list-item) {
--border: 1px solid var(--sl-panel-border-color);
--item-border-top: var(--border);
--item-border-left: var(--border);
--item-border-right: var(--border);
--item-border-bottom: var(--border);
--item-box-shadow: var(--sl-shadow-x-small);
--item-border-radius: var(--sl-border-radius-medium);
display: block;
}

::slotted(btrix-file-list-item:not(:last-of-type)) {
margin-bottom: var(--sl-spacing-x-small);
}
`,
];

@queryAssignedElements({ selector: "btrix-file-list-item" })
listItems!: HTMLElement[];

render() {
return html`<div class="list" role="list">
<slot @slotchange=${this.handleSlotchange}></slot>
</div>`;
}

private handleSlotchange() {
this.listItems.map((el) => {
if (!el.attributes.getNamedItem("role")) {
el.setAttribute("role", "listitem");
}
});
}
}
43 changes: 43 additions & 0 deletions frontend/src/components/ui/file-list/file-list.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { css, html } from "lit";
import { customElement, queryAssignedElements } from "lit/decorators.js";

import { TailwindElement } from "@/classes/TailwindElement";

@customElement("btrix-file-list")
export class FileList extends TailwindElement {
static styles = [
css`
::slotted(btrix-file-list-item) {
--border: 1px solid var(--sl-panel-border-color);
--item-border-top: var(--border);
--item-border-left: var(--border);
--item-border-right: var(--border);
--item-border-bottom: var(--border);
--item-box-shadow: var(--sl-shadow-x-small);
--item-border-radius: var(--sl-border-radius-medium);
display: block;
}

::slotted(btrix-file-list-item:not(:last-of-type)) {
margin-bottom: var(--sl-spacing-x-small);
}
`,
];

@queryAssignedElements({ selector: "btrix-file-list-item" })
listItems!: HTMLElement[];

render() {
return html`<div class="list" role="list">
<slot @slotchange=${this.handleSlotchange}></slot>
</div>`;
}

private handleSlotchange() {
this.listItems.map((el) => {
if (!el.attributes.getNamedItem("role")) {
el.setAttribute("role", "listitem");
}
});
}
}
4 changes: 4 additions & 0 deletions frontend/src/components/ui/file-list/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import "./file-list";
import "./file-list-item";

export type { BtrixFileRemoveEvent as FileRemoveEvent } from "./events";
Loading
Loading