-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix(widgets): Added templating features
- Loading branch information
1 parent
0eb3d1a
commit 4281ae7
Showing
14 changed files
with
519 additions
and
23 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
import * as React from "react"; | ||
import { Tooltip } from './Tooltip'; | ||
|
||
interface FileLoaderProps { | ||
uiLabel: string; | ||
uiTooltip: string; | ||
accept: string; | ||
onFileLoad: (content: Uint8Array, filename: string, encoding: string) => void; | ||
encoding: string; | ||
} | ||
|
||
export function FileLoader({ uiLabel, uiTooltip, accept, onFileLoad }: FileLoaderProps) { | ||
const fileInputRef = React.useRef<HTMLInputElement>(null); | ||
|
||
const handleClick = () => { | ||
fileInputRef.current?.click(); | ||
}; | ||
|
||
const handleFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => { | ||
const file = event.target.files?.[0]; | ||
if (!file) return; | ||
|
||
try { | ||
const arrayBuffer = await file.arrayBuffer(); | ||
const uint8Array = new Uint8Array(arrayBuffer); | ||
|
||
// Detect encoding from the file content | ||
const detectedEncoding = detectEncoding(uint8Array); | ||
console.log(file.name); | ||
console.log(detectedEncoding); | ||
|
||
// Pass both content and detected encoding back | ||
onFileLoad(uint8Array, file.name, detectedEncoding); | ||
} catch (error) { | ||
console.error('Error loading file:', error); | ||
} | ||
}; | ||
|
||
// Simple encoding detection function | ||
const detectEncoding = (data: Uint8Array): string => { | ||
// Check for UTF-8 BOM | ||
if (data.length >= 3 && data[0] === 0xEF && data[1] === 0xBB && data[2] === 0xBF) { | ||
return 'utf-8'; | ||
} | ||
// Check for UTF-16 LE BOM | ||
if (data.length >= 2 && data[0] === 0xFF && data[1] === 0xFE) { | ||
return 'utf-16le'; | ||
} | ||
// Check for UTF-16 BE BOM | ||
if (data.length >= 2 && data[0] === 0xFE && data[1] === 0xFF) { | ||
return 'utf-16be'; | ||
} | ||
// Default to UTF-8 | ||
return 'utf-8'; | ||
}; | ||
|
||
return ( | ||
<div className="file-loader-container"> | ||
<input | ||
type="file" | ||
ref={fileInputRef} | ||
style={{ display: 'none' }} | ||
accept={accept} | ||
onChange={handleFileChange} | ||
/> | ||
<button onClick={handleClick} className="file-loader-button"> | ||
{uiLabel} | ||
{uiTooltip && <Tooltip tooltip={uiTooltip} />} | ||
</button> | ||
</div> | ||
); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,113 @@ | ||
import * as React from "react"; | ||
import { useState, useEffect } from "react"; | ||
import { Tooltip } from './Tooltip'; | ||
|
||
interface SaveFilePickerOptions { | ||
suggestedName?: string; | ||
types?: Array<{ | ||
description: string; | ||
accept: Record<string, string[]>; | ||
}>; | ||
} | ||
|
||
declare global { | ||
interface Window { | ||
showSaveFilePicker(options?: SaveFilePickerOptions): Promise<FileSystemFileHandle>; | ||
} | ||
} | ||
|
||
interface FileSaverProps { | ||
uiLabel: string; | ||
uiTooltip: string; | ||
content: Uint8Array; | ||
suggestedFilename?: string; | ||
mimeType?: string; | ||
fileExtension?: string; | ||
} | ||
|
||
export function FileSaver({ | ||
uiLabel, | ||
uiTooltip, | ||
content, | ||
suggestedFilename, | ||
mimeType = 'application/octet-stream', | ||
fileExtension = '' | ||
}: FileSaverProps) { | ||
const [isInstalled, setIsInstalled] = useState<boolean>(false); | ||
|
||
useEffect(() => { | ||
const checkInstallStatus = async () => { | ||
const isStandalone = window.matchMedia('(display-mode: standalone)').matches; | ||
const isInWebAPKMode = window.matchMedia('(display-mode: minimal-ui)').matches; | ||
const isServiceWorkerRegistered = await navigator.serviceWorker.getRegistration() !== undefined; | ||
|
||
let isInstalledApp = false; | ||
if ('getInstalledRelatedApps' in navigator) { | ||
const installedApps = await (navigator as any).getInstalledRelatedApps(); | ||
isInstalledApp = installedApps.length > 0; | ||
} | ||
|
||
setIsInstalled(isStandalone || isInWebAPKMode || isServiceWorkerRegistered || isInstalledApp); | ||
}; | ||
|
||
checkInstallStatus(); | ||
window.addEventListener('resize', checkInstallStatus); | ||
|
||
return () => { | ||
window.removeEventListener('resize', checkInstallStatus); | ||
}; | ||
}, []); | ||
|
||
const handleClick = async () => { | ||
if (isInstalled && 'showSaveFilePicker' in window) { | ||
try { | ||
const handle = await window.showSaveFilePicker({ | ||
suggestedName: suggestedFilename, | ||
types: [{ | ||
description: 'File', | ||
accept: { | ||
[mimeType]: [fileExtension] | ||
} | ||
}] | ||
}); | ||
|
||
const writable = await handle.createWritable(); | ||
await writable.write(content); | ||
await writable.close(); | ||
} catch (err: unknown) { | ||
if (err instanceof Error && err.name !== 'AbortError') { | ||
console.error('Error saving file:', err); | ||
// Fallback to legacy method if modern method fails | ||
useLegacySaveMethod(); | ||
} | ||
} | ||
} else { | ||
useLegacySaveMethod(); | ||
} | ||
}; | ||
|
||
const useLegacySaveMethod = () => { | ||
const blob = new Blob([content], { type: mimeType }); | ||
const url = URL.createObjectURL(blob); | ||
const a = document.createElement('a'); | ||
a.href = url; | ||
a.download = suggestedFilename || 'download' + fileExtension; | ||
document.body.appendChild(a); | ||
a.click(); | ||
document.body.removeChild(a); | ||
URL.revokeObjectURL(url); | ||
}; | ||
|
||
return ( | ||
<div className="file-saver-container"> | ||
<button | ||
onClick={handleClick} | ||
className="file-saver-button" | ||
disabled={!content} | ||
> | ||
{uiLabel} | ||
{uiTooltip && <Tooltip tooltip={uiTooltip} />} | ||
</button> | ||
</div> | ||
); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
import * as React from "react"; | ||
import { createRender, useModelState } from "@anywidget/react"; | ||
import { FileLoader } from "../ui/FileLoader"; | ||
import '../../css/styles.css'; | ||
|
||
function FileLoaderWidget() { | ||
const [uiLabel] = useModelState<string>("ui_label"); | ||
const [uiTooltip] = useModelState<string>("ui_tooltip"); | ||
const [accept] = useModelState<string>("accept"); | ||
const [, setFileContent] = useModelState<Uint8Array | null>("file_content"); | ||
const [, setFilename] = useModelState<string | null>("filename"); | ||
const [, setEncoding] = useModelState<string>("encoding"); | ||
|
||
const handleFileLoad = (content: Uint8Array, filename: string, encoding: string) => { | ||
console.log("FileLoaderWidget"); | ||
console.log(filename); | ||
console.log(encoding); | ||
console.log(content); | ||
setFileContent(content); | ||
setFilename(filename); | ||
setEncoding(encoding); | ||
}; | ||
|
||
return ( | ||
<FileLoader | ||
uiLabel={uiLabel} | ||
uiTooltip={uiTooltip} | ||
accept={accept} | ||
onFileLoad={handleFileLoad} | ||
/> | ||
); | ||
} | ||
|
||
export default { | ||
render: createRender(FileLoaderWidget) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
import * as React from "react"; | ||
import { createRender, useModelState } from "@anywidget/react"; | ||
import { FileSaver } from "../ui/FileSaver"; | ||
import '../../css/styles.css'; | ||
|
||
function FileSaverWidget() { | ||
const [uiLabel] = useModelState<string>("ui_label"); | ||
const [uiTooltip] = useModelState<string>("ui_tooltip"); | ||
const [content] = useModelState<Uint8Array | null>("content"); | ||
const [suggestedFilename] = useModelState<string | null>("suggested_filename"); | ||
|
||
return ( | ||
<FileSaver | ||
uiLabel={uiLabel} | ||
uiTooltip={uiTooltip} | ||
content={content} | ||
suggestedFilename={suggestedFilename} | ||
/> | ||
); | ||
} | ||
|
||
export default { | ||
render: createRender(FileSaverWidget) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
interface Window { | ||
showSaveFilePicker(options?: { | ||
suggestedName?: string; | ||
}): Promise<FileSystemFileHandle>; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.