import { LightningElement, api } from "lwc"; // Extracts filename and extension from a file URL const FILENAME_FROM_URL_REGEX = /(?=\w+\.\w{3,4}$).+/; const EXTENSION_FROM_URL_REGEX = /\.([^.]*)$/; export default class InteractiveImage extends LightningElement { @api header!: string; @api featuredSrc!: string; @api set downloadUrls(values: any) { // Normalize input values let urls; if (typeof values === "string") { if (values.startsWith("[")) { urls = JSON.parse(values); } else { urls = [values]; } } else { urls = values; } // Ensure that we have some URLs if (!urls || urls.length === 0) { throw new Error( `No download url found for interactive image with title "${this.header}"` ); } // Prepare download options with labels this.urls = urls.map((url: string) => { return { label: this.getDownloadLabelFromUrl(url), id: url }; }); } get downloadUrls() { return this.urls; } private urls: { label: string; id: string }[] = []; private get isSingleDownload() { return this.urls.length === 1; } private get singleDownloadHref() { return this.urls[0].id; } private get singleDownloadFilename() { const pathParts = this.urls[0].id.match(FILENAME_FROM_URL_REGEX); return pathParts ? pathParts[0] : ""; } private get downloadButtonLabel() { return this.isSingleDownload ? this.urls[0].label : "Download as..."; } private handleDownloadOptionChange(event: CustomEvent) { window.open(event.detail, "_blank"); } private getDownloadLabelFromUrl(url: string): string { const urlParts = url.match(EXTENSION_FROM_URL_REGEX); return urlParts ? `Download as ${urlParts[1].toUpperCase()}` : "Download"; } }