Skip to content
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

Convert Meditor.vue to <script setup> #1303

Merged
merged 2 commits into from
Nov 29, 2022
Merged
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
332 changes: 141 additions & 191 deletions web/src/components/Meditor/Meditor.vue
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
<!-- eslint-disable vue/multi-word-component-names -->
<template>
<v-dialog
v-model="open"
Expand Down Expand Up @@ -57,18 +58,18 @@
<template #activator="{ on }">
<v-icon
left
:color="allModelsValid ? 'success' : 'error'"
:color="modelValid ? 'success' : 'error'"
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note, this was aliased as allModelsValid in the returned object of the original setup() function. Instead of replicating that behavior in the new <script> section, I think it's clearer to just use the modelValid variable directly.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

v-on="on"
>
<template v-if="allModelsValid">
<template v-if="modelValid">
mdi-checkbox-marked-circle
</template>
<template v-else>
mdi-alert-circle
</template>
</v-icon>
</template>
<template v-if="allModelsValid">
<template v-if="modelValid">
All metadata for this dandiset is valid.
</template>
<template v-else>
Expand Down Expand Up @@ -222,11 +223,11 @@
</v-dialog>
</template>

<script lang="ts">
<script setup lang="ts">
import type { JSONSchema7 } from 'json-schema';

import {
defineComponent, ref, computed, ComputedRef, onMounted,
ref, computed, ComputedRef, onMounted,
} from 'vue';

import jsYaml from 'js-yaml';
Expand Down Expand Up @@ -266,203 +267,152 @@ function renderField(fieldSchema: JSONSchema7) {
return true;
}

export default defineComponent({
// eslint-disable-next-line vue/multi-word-component-names
name: 'Meditor',
components: { VJsf, VJsfWrapper },
setup() {
const store = useDandisetStore();

const currentDandiset = computed(() => store.dandiset);
const id = computed(() => currentDandiset.value?.dandiset.identifier);
const schema: ComputedRef<JSONSchema7> = computed(() => store.schema);
const model = computed(() => currentDandiset.value?.metadata);
const readonly = computed(() => !store.userCanModifyDandiset);
const isDataInLocalStorage = computed(
() => (model.value ? dataInLocalStorage(model.value.id) : false),
);

const invalidPermissionSnackbar = ref(false);
const tab = ref(null);
const loadFromLocalStoragePrompt = ref(false);

editorInterface.value = new EditorInterface(schema.value, model.value as DandiModel);
const {
modelValid,
basicSchema,
basicModel,
basicModelValid,
complexSchema,
complexModel,
setComplexModelProp,
complexModelValid,
complexModelValidation,
transactionTracker,
} = editorInterface.value;
const CommonVJSFOptions = computed(() => ({
initialValidation: 'all',
disableAll: readonly.value,
autoFixArrayItems: false,
childrenClass: 'px-2',
fieldProps: {
outlined: true,
dense: true,
},
arrayItemCardProps: {
outlined: true,
dense: true,
},
editMode: 'inline',
hideReadOnly: true,
}));

// undo/redo functionality
function undoChange() {
transactionTracker.undo();
}
function redoChange() {
transactionTracker.redo();
}
const disableUndo = computed(
() => readonly.value || !transactionTracker.areTransactionsBehind(),
);
const disableRedo = computed(
() => readonly.value || !transactionTracker.areTransactionsAhead(),
);
const vjsfListener = () => transactionTracker.add(basicModel.value, false);
const modified = computed(() => transactionTracker.isModified());

async function save() {
if (!id.value || !model.value || !currentDandiset.value?.version) {
return;
}
const dandiset = editorInterface.value?.getModel();

try {
const { status, data } = await dandiRest.saveDandiset(
id.value, currentDandiset.value.version, dandiset,
);

if (status === 200) {
clearLocalStorage(model.value.id);
// wait 0.5 seconds to give the celery worker some time to finish validation
setTimeout(async () => {
await store.fetchDandiset({
identifier: data.dandiset.identifier,
version: data.version,
});
transactionTracker.reset();
}, 500);
}
} catch (error) {
if (axios.isAxiosError(error) && error.response?.status === 403) {
invalidPermissionSnackbar.value = true;
}

throw error;
}
}

// TODO: Add back UI to toggle YAML vs JSON
const yamlOutput = ref(false);
const contentType = computed(() => (yamlOutput.value ? 'text/yaml' : 'application/json'));
const output = computed(() => {
const currentModel = editorInterface.value?.getModel();
return yamlOutput.value ? jsYaml.dump(currentModel) : JSON.stringify(currentModel, null, 2);
});

function download() {
const blob = new Blob([output.value], { type: contentType.value });

const extension = contentType.value.split('/')[1];
const filename = `dandiset.${extension}`;
const link = document.createElement('a');

link.href = URL.createObjectURL(blob);
link.download = filename;
link.click();
URL.revokeObjectURL(link.href);
}

function getSchemaTitle(propKey: string) {
const properties = complexSchema?.properties as any;
return properties ? properties[propKey].title || propKey : propKey;
}
const store = useDandisetStore();

const currentDandiset = computed(() => store.dandiset);
const id = computed(() => currentDandiset.value?.dandiset.identifier);
const schema: ComputedRef<JSONSchema7> = computed(() => store.schema);
const model = computed(() => currentDandiset.value?.metadata);
const readonly = computed(() => !store.userCanModifyDandiset);
const isDataInLocalStorage = computed(
() => (model.value ? dataInLocalStorage(model.value.id) : false),
);

const invalidPermissionSnackbar = ref(false);
const tab = ref(null);
const loadFromLocalStoragePrompt = ref(false);

editorInterface.value = new EditorInterface(schema.value, model.value as DandiModel);
const {
modelValid,
basicSchema,
basicModel,
basicModelValid,
complexSchema,
complexModelValidation,
transactionTracker,
} = editorInterface.value;
const CommonVJSFOptions = computed(() => ({
initialValidation: 'all',
disableAll: readonly.value,
autoFixArrayItems: false,
childrenClass: 'px-2',
fieldProps: {
outlined: true,
dense: true,
},
arrayItemCardProps: {
outlined: true,
dense: true,
},
editMode: 'inline',
hideReadOnly: true,
}));

const fieldsToRender = Object.keys(complexSchema.properties as any).filter(
(p) => renderField((complexSchema as any).properties[p]),
// undo/redo functionality
function undoChange() {
transactionTracker.undo();
}
function redoChange() {
transactionTracker.redo();
}
const disableUndo = computed(
() => readonly.value || !transactionTracker.areTransactionsBehind(),
);
const disableRedo = computed(
() => readonly.value || !transactionTracker.areTransactionsAhead(),
);
const vjsfListener = () => transactionTracker.add(basicModel.value, false);
const modified = computed(() => transactionTracker.isModified());

async function save() {
if (!id.value || !model.value || !currentDandiset.value?.version) {
return;
}
const dandiset = editorInterface.value?.getModel();

try {
const { status, data } = await dandiRest.saveDandiset(
id.value, currentDandiset.value.version, dandiset,
);

function loadDataFromLocalStorage() {
if (!model.value) {
return;
}
// load previous meditor data from localStorage
editorInterface.value?.setModel(getModelLocalStorage(model.value.id));
editorInterface.value?.transactionTracker.setTransactions(
getTransactionsLocalStorage(model.value.id),
);
editorInterface.value?.transactionTracker.setTransactionPointer(
getTransactionPointerLocalStorage(model.value.id),
);
loadFromLocalStoragePrompt.value = false;
}
function discardDataFromLocalStorage() {
if (!model.value) {
return;
}
if (status === 200) {
clearLocalStorage(model.value.id);
loadFromLocalStoragePrompt.value = false;
// wait 0.5 seconds to give the celery worker some time to finish validation
setTimeout(async () => {
await store.fetchDandiset({
identifier: data.dandiset.identifier,
version: data.version,
});
transactionTracker.reset();
}, 500);
}
} catch (error) {
if (axios.isAxiosError(error) && error.response?.status === 403) {
invalidPermissionSnackbar.value = true;
}
onMounted(() => {
// On mount, detect if there is unsaved data stored in local storage and ask the user
// if they would like to restore it
if (isDataInLocalStorage.value) {
loadFromLocalStoragePrompt.value = true;
}
});

return {
allModelsValid: modelValid,
tab,
schema,
model,
readonly,
open,

basicSchema,
basicModel,
basicModelValid,
vjsfListener,

complexSchema,
complexModel,
complexModelValid,
complexModelValidation,
throw error;
}
}

invalidPermissionSnackbar,
fieldsToRender,
getSchemaTitle,
save,
download,
// TODO: Add back UI to toggle YAML vs JSON
const yamlOutput = ref(false);
const contentType = computed(() => (yamlOutput.value ? 'text/yaml' : 'application/json'));
const output = computed(() => {
const currentModel = editorInterface.value?.getModel();
return yamlOutput.value ? jsYaml.dump(currentModel) : JSON.stringify(currentModel, null, 2);
});

modified,
undoChange,
redoChange,
disableUndo,
disableRedo,
function download() {
const blob = new Blob([output.value], { type: contentType.value });

CommonVJSFOptions,
const extension = contentType.value.split('/')[1];
const filename = `dandiset.${extension}`;
const link = document.createElement('a');

setComplexModelProp,
link.href = URL.createObjectURL(blob);
link.download = filename;
link.click();
URL.revokeObjectURL(link.href);
}

editorInterface,
transactionTracker,
function getSchemaTitle(propKey: string) {
const properties = complexSchema?.properties as any;
return properties ? properties[propKey].title || propKey : propKey;
}

loadFromLocalStoragePrompt,
loadDataFromLocalStorage,
discardDataFromLocalStorage,
};
},
const fieldsToRender = Object.keys(complexSchema.properties as any).filter(
(p) => renderField((complexSchema as any).properties[p]),
);

function loadDataFromLocalStorage() {
if (!model.value) {
return;
}
// load previous meditor data from localStorage
editorInterface.value?.setModel(getModelLocalStorage(model.value.id));
editorInterface.value?.transactionTracker.setTransactions(
getTransactionsLocalStorage(model.value.id),
);
editorInterface.value?.transactionTracker.setTransactionPointer(
getTransactionPointerLocalStorage(model.value.id),
);
loadFromLocalStoragePrompt.value = false;
}
function discardDataFromLocalStorage() {
if (!model.value) {
return;
}
clearLocalStorage(model.value.id);
loadFromLocalStoragePrompt.value = false;
}
onMounted(() => {
// On mount, detect if there is unsaved data stored in local storage and ask the user
// if they would like to restore it
if (isDataInLocalStorage.value) {
loadFromLocalStoragePrompt.value = true;
}
});

</script>