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

Add script selection Import/Export feature #453

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
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
2 changes: 2 additions & 0 deletions src/infrastructure/Dialog/Browser/FileSaverDialog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,6 @@ const MimeTypes: Record<FileType, string> = {
// otherwise they ignore extension and save the file as text.
[FileType.BatchFile]: 'application/bat', // https://en.wikipedia.org/wiki/Batch_file
[FileType.ShellScript]: 'text/x-shellscript', // https://de.wikipedia.org/wiki/Shellskript#MIME-Typ
[FileType.Json]: 'application/json', // https://en.wikipedia.org/wiki/JSON

} as const;
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,12 @@ const FileTypeSpecificFilters: Record<FileType, Electron.FileFilter[]> = {
extensions: ['sh', 'bash', 'zsh'],
},
],
[FileType.Json]: [
{
name: 'JSON Files',
extensions: ['json'],
},
],
};

type SaveDialogOutcome =
Expand Down
4 changes: 4 additions & 0 deletions src/presentation/assets/icons/floppy-disk-gear.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions src/presentation/common/Dialog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export interface Dialog {
export enum FileType {
BatchFile,
ShellScript,
Json,
}

export type SaveFileOutcome = SuccessfulSaveFile | FailedSaveFile;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<template>
<IconButton
text="Save Selection"
icon-name="floppy-disk-gear"
@click="saveSelection"
/>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import { injectKey } from '@/presentation/injectionSymbols';
import { FileType } from '@/presentation/common/Dialog';
import IconButton from '../IconButton.vue';
import { createScriptErrorDialog } from '../ScriptErrorDialog';

interface SelectionConfig {
version: string;
timestamp: string;
selectedScripts: string[];
}

export default defineComponent({
components: {
IconButton,
},
setup() {
const { currentSelection } = injectKey((keys) => keys.useUserSelectionState);
const { dialog } = injectKey((keys) => keys.useDialog);
const { projectDetails } = injectKey((keys) => keys.useApplication);
const { scriptDiagnosticsCollector } = injectKey((keys) => keys.useScriptDiagnosticsCollector);

async function saveSelection() {
const config: SelectionConfig = {
version: projectDetails.version.toString(),
timestamp: new Date().toISOString(),
selectedScripts: currentSelection.value.scripts.selectedScripts.map((script) => script.id),
};

const { success, error } = await dialog.saveFile(
JSON.stringify(config, null, 2),
'privacy-selection.json',
FileType.Json,
);

if (!success) {
dialog.showError(...(await createScriptErrorDialog({
errorContext: 'save',
errorType: error.type,
errorMessage: error.message,
isFileReadbackError: error.type === 'FileReadbackVerificationError',
}, scriptDiagnosticsCollector)));
}
}

return {
saveSelection,
};
},
});
</script>
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
<div v-if="hasCode" class="container">
<CodeRunButton class="code-button" />
<CodeSaveButton class="code-button" />
<SaveSelectionButton class="code-button" />
<CodeCopyButton class="code-button" />
</div>
</template>
Expand All @@ -14,12 +15,14 @@ import { injectKey } from '@/presentation/injectionSymbols';
import CodeRunButton from './CodeRunButton.vue';
import CodeCopyButton from './CodeCopyButton.vue';
import CodeSaveButton from './Save/CodeSaveButton.vue';
import SaveSelectionButton from './Save/SaveSelectionButton.vue';

export default defineComponent({
components: {
CodeRunButton,
CodeCopyButton,
CodeSaveButton,
SaveSelectionButton,
},
setup() {
const { currentCode } = injectKey((keys) => keys.useCurrentCode);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,12 +81,32 @@
/>
</template>
</TooltipWrapper>

<!-- Load from file -->
<TooltipWrapper>
<MenuOptionListItem
label="Import"
:enabled="!isImporting"
@click="loadFromFile"
/>
<template #tooltip>
<RecommendationDocumentation
:privacy-rating="0"
description="Restores a previously saved script selection from a JSON file."
recommendation="..."
:considerations="[
'All current selections will be cleared before import',
'Only .json files exported by privacy.sexy are supported',
]"
/>
</template>
</TooltipWrapper>
</MenuOptionList>
</template>

<script lang="ts">
import {
defineComponent, computed,
defineComponent, computed, ref,
} from 'vue';
import { injectKey } from '@/presentation/injectionSymbols';
import TooltipWrapper from '@/presentation/components/Shared/TooltipWrapper.vue';
Expand All @@ -97,6 +117,12 @@ import { setCurrentRecommendationStatus, getCurrentRecommendationStatus } from '
import { RecommendationStatusType } from './RecommendationStatusType';
import RecommendationDocumentation from './RecommendationDocumentation.vue';

interface SavedSelection {
version?: string;
timestamp?: string;
selectedScripts: string[];
}

export default defineComponent({
components: {
MenuOptionList,
Expand All @@ -109,6 +135,7 @@ export default defineComponent({
currentSelection, modifyCurrentSelection,
} = injectKey((keys) => keys.useUserSelectionState);
const { currentState } = injectKey((keys) => keys.useCollectionState);
const { dialog } = injectKey((keys) => keys.useDialog);

const currentCollection = computed<ICategoryCollection>(() => currentState.value.collection);

Expand All @@ -122,6 +149,8 @@ export default defineComponent({
},
});

const isImporting = ref(false);

function selectRecommendationStatusType(type: RecommendationStatusType) {
if (currentRecommendationStatusType.value === type) {
return;
Expand All @@ -134,10 +163,103 @@ export default defineComponent({
});
}

async function loadFromFile() {
if (isImporting.value) {
return;
}

try {
isImporting.value = true;
const input = document.createElement('input');
input.type = 'file';
input.accept = '.json';

const file = await new Promise<File>((resolve, reject) => {
input.onchange = (event) => {
const { files } = (event.target as HTMLInputElement);
if (files && files.length > 0) {
resolve(files[0]);
} else {
reject(new Error('No file selected'));
}
};
input.click();
});

const content = await new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result as string);
reader.onerror = () => reject(new Error('Failed to read file'));
reader.readAsText(file);
});

let savedSelection: SavedSelection;
try {
savedSelection = JSON.parse(content) as SavedSelection;
if (!Array.isArray(savedSelection.selectedScripts)) {
throw new Error('Invalid file format: missing or invalid scripts array');
}
} catch (parseError) {
dialog.showError('Import Error', 'The selected file is not a valid selection file.');
return;
}

// Update the current selection state
await modifyCurrentSelection((selection) => {
// First deselect all scripts
selection.scripts.deselectAll();

// Validate and apply each script selection
const validScripts = savedSelection.selectedScripts.filter(
(scriptId) => {
try {
return currentCollection.value.getScript(scriptId) !== undefined;
} catch {
return false;
}
},
);

if (validScripts.length === 0) {
throw new Error('No valid scripts found in the imported selection');
}

if (validScripts.length !== savedSelection.selectedScripts.length) {
dialog.showError(
'Import Warning',
'Some scripts from the imported selection were not found in the current collection.',
);
}

// Apply valid script selections
validScripts.forEach((scriptId) => {
selection.scripts.processChanges({
changes: [{
scriptId,
newStatus: {
isSelected: true,
isReverted: false,
},
}],
});
});
});
} catch (error) {
if (error instanceof Error && error.message !== 'No file selected') {
dialog.showError('Import Error', `Failed to import selection: ${error.message}`);
console.error('Failed to load selection:', error);
}
} finally {
isImporting.value = false;
}
}

return {
RecommendationStatusType,
currentRecommendationStatusType,
selectRecommendationStatusType,
loadFromFile,
isImporting,
};
},
});
Expand Down
1 change: 1 addition & 0 deletions src/presentation/components/Shared/Icon/IconName.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export const IconNames = [
'left-right',
'file-arrow-down',
'floppy-disk',
'floppy-disk-gear',
'play',
'lightbulb',
'square-check',
Expand Down
Loading