use showOpenFilePicker()

This commit is contained in:
Joscha
2025-01-06 16:54:50 +01:00
parent c6174a57d9
commit 3b1174f9ee
+27 -16
View File
@@ -135,19 +135,28 @@ class ModalOpenInternal extends React.Component<ModalOpenInternalProps, ModalOpe
this.onStyleSelect(this.state.styleUrl); this.onStyleSelect(this.state.styleUrl);
} }
onUpload = (_: any, files: Result[]) => { onOpenFile = async () => {
const [, file] = files[0];
const reader = new FileReader();
this.clearError(); this.clearError();
reader.readAsText(file, "UTF-8"); const pickerOpts = {
reader.onload = e => { types: [
{
description: "Style JSON",
accept: {"application/json": [".json"]},
},
],
excludeAcceptAllOption: true,
multiple: false,
};
const [fileHandle] = await window.showOpenFilePicker(pickerOpts);
const file = await fileHandle.getFile();
const content = await file.text();
let mapStyle; let mapStyle;
try { try {
mapStyle = JSON.parse(e.target?.result as string) mapStyle = JSON.parse(content)
} } catch (err) {
catch(err) {
this.setState({ this.setState({
error: (err as Error).toString() error: (err as Error).toString()
}); });
@@ -156,8 +165,7 @@ class ModalOpenInternal extends React.Component<ModalOpenInternalProps, ModalOpe
mapStyle = style.ensureStyleValidity(mapStyle) mapStyle = style.ensureStyleValidity(mapStyle)
this.props.onStyleOpen(mapStyle); this.props.onStyleOpen(mapStyle);
this.onOpenToggle(); this.onOpenToggle();
} return file;
reader.onerror = e => console.log(e.target);
} }
onOpenToggle() { onOpenToggle() {
@@ -206,11 +214,14 @@ class ModalOpenInternal extends React.Component<ModalOpenInternalProps, ModalOpe
> >
{errorElement} {errorElement}
<section className="maputnik-modal-section"> <section className="maputnik-modal-section">
<h1>{t("Upload Style")}</h1> <h1>{t("Open local Style")}</h1>
<p>{t("Upload a JSON style from your computer.")}</p> <p>{t("Open a local JSON style from your computer.")}</p>
<FileReaderInput onChange={this.onUpload} tabIndex={-1} aria-label={t("Style file")}> <div>
<InputButton className="maputnik-upload-button"><MdFileUpload /> {t("Upload")}</InputButton> <InputButton
</FileReaderInput> className="maputnik-big-button"
onClick={this.onOpenFile}><MdFileUpload/> {t("Open Style")}
</InputButton>
</div>
</section> </section>
<section className="maputnik-modal-section"> <section className="maputnik-modal-section">