Skip to content

📚 The open-source, offline-first Notion, Obsidian & Confluence alternative. Advanced Markdown, multi-tenant teams, OIDC/SSO, and local S3 backups. Deploy in one command.

New snippets system

Smaug67396dc97ea992f8
diff --git a/frontend/app/components/DataTable.vue b/frontend/app/components/DataTable.vue
index a2fc7156..4cf38dcc 100644
--- a/frontend/app/components/DataTable.vue
+++ b/frontend/app/components/DataTable.vue
@@ -14,7 +14,7 @@
<th>
<input type="checkbox" style="width: 20px" :checked="selectedRows.length > 0" @change="toggleSelectAll" />
</th>
- <th v-for="header in headers" :key="header.key">
+ <th v-for="header in headers" :key="header.key" :class="header.align && `align-${header.align}`">
{{ header.label }}
</th>
</tr>
@@ -25,7 +25,7 @@
<td>
<input v-model="selectedRows" type="checkbox" :value="row" style="width: 20px" />
</td>
- <td v-for="header in headers" :key="header.key">
+ <td v-for="header in headers" :key="header.key" :class="header.align && `align-${header.align}`">
<!-- eslint-disable-next-line vue/no-v-html -->
<span v-if="row[header.key]?.type === 'html'" v-html="row[header.key]?.content" />
<span v-else-if="row[header.key]?.type === 'slot'">
@@ -128,6 +128,7 @@ const shouldShowEllipsisBefore = computed(() => {
interface Header {
key: string;
label: string;
+ align?: 'left' | 'center' | 'right';
}
export interface Field<V = unknown> {
[key: string]: {
@@ -178,12 +179,37 @@ th {
font-size: 13px;
color: var(--font-color-dark);
background: var(--bg-ui);
+
+ &.align-right {
+ text-align: right;
+ padding-right: 30px;
+ }
+
+ &.align-center {
+ text-align: center;
+ }
text-transform: uppercase;
}
td {
color: var(--font-color-light);
+ &.align-right {
+ text-align: right;
+ padding-right: 10px;
+ > span {
+ justify-content: flex-end;
+ }
+ }
+
+ &.align-center {
+ text-align: center;
+
+ > span {
+ justify-content: center;
+ }
+ }
+
> span {
display: flex;
align-items: center;
diff --git a/frontend/app/components/Node/Modals/Delete.vue b/frontend/app/components/Node/Modals/Delete.vue
index 54f18bdd..f3f9be8f 100644
--- a/frontend/app/components/Node/Modals/Delete.vue
+++ b/frontend/app/components/Node/Modals/Delete.vue
@@ -54,7 +54,7 @@ const handleDelete = async () => {
} else if (props.node) {
await store.delete(props.node.id);
}
- emit('close', 'success');
+ emit('close');
if (props.redirectTo) {
useRouter().push(props.redirectTo);
}
diff --git a/frontend/app/composables/Preferences.ts b/frontend/app/composables/Preferences.ts
index 3207dc08..3b55537b 100644
--- a/frontend/app/composables/Preferences.ts
+++ b/frontend/app/composables/Preferences.ts
@@ -36,7 +36,6 @@ export const DEFAULT_PREFERENCES = {
{ id: ':::grey', label: ':::grey\n${0}\n:::' },
{ id: ':::details', label: ':::details\n${0}\n:::' },
{ id: ':::center', label: ':::center\n${0}\n:::' },
- { id: ':::m', label: '${0}$' },
{ id: ':::property', label: ':::property ${0}\n\n:::' },
{ id: ':::warning', label: ':::warning ${0}\n\n:::' },
] as ANode<string>[],
diff --git a/frontend/app/composables/useSnippets.ts b/frontend/app/composables/useSnippets.ts
new file mode 100644
index 00000000..761df1bc
--- /dev/null
+++ b/frontend/app/composables/useSnippets.ts
@@ -0,0 +1,244 @@
+/**
+ * Snippets management composable
+ * Handles CRUD operations, import/export, and filtering
+ */
+
+export interface Snippet {
+ id: string;
+ label: string;
+}
+
+export function useSnippets() {
+ const preferences = usePreferences();
+ const notifications = useNotifications();
+ const snippets = preferences.get('snippets');
+
+ // State
+ const search = ref('');
+ const editingId = ref<string | null>(null);
+ const editBuffer = ref<Snippet>({ id: '', label: '' });
+ const selectedIds = ref<Set<string>>(new Set());
+
+ // Filtered & sorted snippets
+ const filtered = computed(() => {
+ const q = search.value.toLowerCase().trim();
+ if (!q) return snippets.value;
+ return snippets.value.filter(s => s.id.toLowerCase().includes(q) || s.label.toLowerCase().includes(q));
+ });
+
+ // Selection helpers
+ const isSelected = (id: string) => selectedIds.value.has(id);
+ const toggleSelect = (id: string) => {
+ if (selectedIds.value.has(id)) {
+ selectedIds.value.delete(id);
+ } else {
+ selectedIds.value.add(id);
+ }
+ selectedIds.value = new Set(selectedIds.value); // Trigger reactivity
+ };
+ const selectAll = () => {
+ filtered.value.forEach(s => selectedIds.value.add(s.id));
+ selectedIds.value = new Set(selectedIds.value);
+ };
+ const deselectAll = () => {
+ selectedIds.value.clear();
+ selectedIds.value = new Set();
+ };
+ const isAllSelected = computed(() => filtered.value.length > 0 && filtered.value.every(s => selectedIds.value.has(s.id)));
+
+ // Validation
+ const isDuplicate = (id: string, excludeOriginal?: string) => {
+ return snippets.value.some(s => s.id === id && s.id !== excludeOriginal);
+ };
+
+ // CRUD
+ const add = (snippet: Snippet): boolean => {
+ if (!snippet.id.trim() || isDuplicate(snippet.id)) {
+ notifications.add({ title: 'Invalid or duplicate shortcut', type: 'error' });
+ return false;
+ }
+ snippets.value = [snippet, ...snippets.value];
+ preferences.set('snippets', snippets.value);
+ notifications.add({ title: 'Snippet added', type: 'success' });
+ return true;
+ };
+
+ const update = (originalId: string, updated: Snippet): boolean => {
+ if (!updated.id.trim() || isDuplicate(updated.id, originalId)) {
+ notifications.add({ title: 'Invalid or duplicate shortcut', type: 'error' });
+ return false;
+ }
+ const idx = snippets.value.findIndex(s => s.id === originalId);
+ if (idx !== -1) {
+ snippets.value[idx] = { ...updated };
+ snippets.value = [...snippets.value];
+ preferences.set('snippets', snippets.value);
+ }
+ return true;
+ };
+
+ const remove = (id: string) => {
+ snippets.value = snippets.value.filter(s => s.id !== id);
+ preferences.set('snippets', snippets.value);
+ selectedIds.value.delete(id);
+ selectedIds.value = new Set(selectedIds.value);
+ };
+
+ const removeSelected = () => {
+ const count = selectedIds.value.size;
+ snippets.value = snippets.value.filter(s => !selectedIds.value.has(s.id));
+ preferences.set('snippets', snippets.value);
+ deselectAll();
+ notifications.add({ title: `${count} snippet(s) deleted`, type: 'success' });
+ };
+
+ const restoreDefaults = () => {
+ snippets.value = [...DEFAULT_PREFERENCES.snippets];
+ preferences.set('snippets', snippets.value);
+ deselectAll();
+ notifications.add({ title: 'Defaults restored', type: 'success' });
+ };
+
+ // Edit helpers
+ const startEdit = (snippet: Snippet) => {
+ editingId.value = snippet.id;
+ editBuffer.value = { ...snippet };
+ };
+
+ const cancelEdit = () => {
+ editingId.value = null;
+ editBuffer.value = { id: '', label: '' };
+ };
+
+ const saveEdit = (): boolean => {
+ if (!editingId.value) return false;
+ const success = update(editingId.value, editBuffer.value);
+ if (success) cancelEdit();
+ return success;
+ };
+
+ // Import/Export
+ const exportJSON = () => {
+ const blob = new Blob([JSON.stringify(snippets.value, null, 2)], { type: 'application/json' });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = 'alexandrie-snippets.json';
+ a.click();
+ URL.revokeObjectURL(url);
+ notifications.add({ title: 'Snippets exported', type: 'success' });
+ };
+
+ const importJSON = (file: File): Promise<number> => {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = e => {
+ try {
+ const data = JSON.parse(e.target?.result as string);
+ if (!Array.isArray(data)) throw new Error('Invalid format');
+
+ const existingIds = new Set(snippets.value.map(s => s.id));
+ const newSnippets = data.filter((s: unknown) => {
+ const snippet = s as Snippet;
+ return snippet?.id && snippet?.label && !existingIds.has(snippet.id);
+ });
+
+ snippets.value = [...snippets.value, ...newSnippets];
+ preferences.set('snippets', snippets.value);
+ resolve(newSnippets.length);
+ } catch {
+ reject(new Error('Invalid JSON format'));
+ }
+ };
+ reader.onerror = () => reject(new Error('Failed to read file'));
+ reader.readAsText(file);
+ });
+ };
+
+ /**
+ * Import dictionary from text file (Google Dictionary format)
+ * Format: one word/phrase per line, or "shortcut:content" per line
+ */
+ const importDictionary = (file: File): Promise<number> => {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = e => {
+ try {
+ const text = e.target?.result as string;
+ const lines = text.split(/\r?\n/).filter(l => l.trim());
+
+ const existingIds = new Set(snippets.value.map(s => s.id));
+ const newSnippets: Snippet[] = [];
+
+ for (const line of lines) {
+ // Format: "shortcut:content" or just "word" (word becomes both shortcut and content)
+ const colonIdx = line.indexOf(':');
+ let id: string;
+ let label: string;
+
+ if (colonIdx > 0) {
+ id = line.slice(0, colonIdx).trim();
+ label = line.slice(colonIdx + 1).trim();
+ } else {
+ const word = line.trim();
+ id = word.toLowerCase().replace(/\s+/g, '_');
+ label = word;
+ }
+
+ if (id && label && !existingIds.has(id)) {
+ newSnippets.push({ id, label });
+ existingIds.add(id);
+ }
+ }
+
+ snippets.value = [...snippets.value, ...newSnippets];
+ preferences.set('snippets', snippets.value);
+ resolve(newSnippets.length);
+ } catch {
+ reject(new Error('Failed to parse dictionary'));
+ }
+ };
+ reader.onerror = () => reject(new Error('Failed to read file'));
+ reader.readAsText(file);
+ });
+ };
+
+ // Clear search when it changes
+ watch(search, () => deselectAll());
+
+ return {
+ // State
+ snippets: filtered,
+ allSnippets: snippets,
+ search,
+ editingId,
+ editBuffer,
+ selectedIds,
+ selectedCount: computed(() => selectedIds.value.size),
+
+ // Selection
+ isSelected,
+ toggleSelect,
+ selectAll,
+ deselectAll,
+ isAllSelected,
+
+ // CRUD
+ add,
+ update,
+ remove,
+ removeSelected,
+ restoreDefaults,
+
+ // Edit
+ startEdit,
+ cancelEdit,
+ saveEdit,
+ isDuplicate,
+
+ // Import/Export
+ exportJSON,
+ importJSON,
+ importDictionary,
+ };
+}
diff --git a/frontend/app/pages/dashboard/settings/_views/_modals/Restore.vue b/frontend/app/pages/dashboard/settings/_views/_modals/Restore.vue
new file mode 100644
index 00000000..14e59ad6
--- /dev/null
+++ b/frontend/app/pages/dashboard/settings/_views/_modals/Restore.vue
@@ -0,0 +1,24 @@
+<template>
+ <div class="modal">
+ <h3>Restore default snippets</h3>
+ <p>Are you sure you want to restore the default snippets?</p>
+
+ <p class="description">This action is irreversible</p>
+
+ <div class="footer">
+ <AppButton type="secondary" @click="emit('close')">Cancel</AppButton>
+ <AppButton type="danger" @click="reset">Confirm</AppButton>
+ </div>
+ </div>
+</template>
+
+<script setup lang="ts">
+const snippets = useSnippets();
+
+const emit = defineEmits<{ close: [] }>();
+
+const reset = async () => {
+ snippets.restoreDefaults();
+ emit('close');
+};
+</script>
diff --git a/frontend/app/pages/dashboard/settings/_views/_modals/SnippetModal.vue b/frontend/app/pages/dashboard/settings/_views/_modals/SnippetModal.vue
new file mode 100644
index 00000000..93c0fad9
--- /dev/null
+++ b/frontend/app/pages/dashboard/settings/_views/_modals/SnippetModal.vue
@@ -0,0 +1,59 @@
+<template>
+ <div class="modal">
+ <h2>{{ isEdit ? 'Edit Snippet' : 'New Snippet' }}</h2>
+
+ <label>
+ <span>Shortcut</span>
+ <input v-model="form.id" type="text" placeholder="!example" :class="{ error: formError }" @input="formError = ''" />
+ <small v-if="formError" class="error-text">{{ formError }}</small>
+ <small v-else class="hint">Prefix with <code>!</code> for easy trigger in editor</small>
+ </label>
+
+ <label> Content </label>
+ <textarea v-model="form.label" rows="6" placeholder="Snippet content...&#10;Use ${0}, ${1} for tab stops" />
+ <div class="actions-row">
+ <AppButton type="secondary" @click="$emit('close')">Cancel</AppButton>
+ <AppButton type="primary" @click="save">{{ isEdit ? 'Save' : 'Create' }}</AppButton>
+ </div>
+ </div>
+</template>
+
+<script setup lang="ts">
+import type { Snippet } from '~/composables/useSnippets';
+
+const props = defineProps<{
+ snippet?: Snippet;
+ onSave: (snippet: Snippet, originalId?: string) => boolean;
+}>();
+
+const emit = defineEmits<{ close: [] }>();
+
+const isEdit = computed(() => !!props.snippet);
+const form = ref<Snippet>({ id: props.snippet?.id ?? '', label: props.snippet?.label ?? '' });
+const formError = ref('');
+
+const save = () => {
+ const trimmedId = form.value.id.trim();
+ if (!trimmedId) {
+ formError.value = 'Shortcut is required';
+ return;
+ }
+
+ const success = props.onSave({ id: trimmedId, label: form.value.label }, isEdit.value ? props.snippet?.id : undefined);
+
+ if (success) {
+ emit('close');
+ } else {
+ formError.value = 'This shortcut already exists';
+ }
+};
+</script>
+
+<style scoped lang="scss">
+textarea {
+ width: 100%;
+}
+.actions-row {
+ justify-content: flex-end;
+}
+</style>
diff --git a/frontend/app/pages/dashboard/settings/_views/snippets.vue b/frontend/app/pages/dashboard/settings/_views/snippets.vue
index 6288af02..0f24a6fe 100644
--- a/frontend/app/pages/dashboard/settings/_views/snippets.vue
+++ b/frontend/app/pages/dashboard/settings/_views/snippets.vue
@@ -1,540 +1,324 @@
<template>
- <div>
- <div class="header">
- <h2 class="app-title">Snippets</h2>
- <p class="app-subtitle">Manage your markdown snippets for quick insertion. Use shortcuts like !blue to quickly insert pre-defined content.</p>
- </div>
- <!-- Search and Actions -->
- <div class="toolbar">
- <div class="search-section">
- <div class="search-wrapper">
- <Icon name="search" class="search-icon" /> <input v-model="searchQuery" type="text" placeholder="Search snippets..." class="search-input" />
- </div>
- <div class="filter-section"><AppSelect v-model="sortBy" :items="sortOptions" placeholder="Sort by..." size="200px" :searchable="false" /></div>
- </div>
- <div class="actions-row">
- <AppButton v-if="selectedSnippets.length > 0" type="danger" @click="deleteSelected"> Delete Selected ({{ selectedSnippets.length }}) </AppButton>
- <AppButton type="secondary" @click="exportSnippets"><Icon name="backup" /> Export </AppButton>
- <AppButton type="secondary" @click="importSnippets"><Icon name="import" /> Import </AppButton>
- <AppButton type="secondary" @click="restoreDefaults"> ↺ Restore defaults</AppButton>
- <AppButton type="primary" @click="addSnippet"> + Add Snippet </AppButton>
- </div>
- </div>
- <div class="snippets-container">
- <div v-if="filteredSnippets.length === 0 && !creatingSnippet" class="no-snippets">
- <Icon name="search" class="no-snippets-icon" />
- <p v-if="searchQuery">No snippets found matching "{{ searchQuery }}"</p>
- <p v-else>No snippets available. Create your first snippet!</p>
+ <div class="snippets-page">
+ <!-- Header -->
+ <header class="page-header">
+ <div class="header-content">
+ <h2 class="app-title">Snippets</h2>
+ <p class="app-subtitle">
+ Manage markdown shortcuts. Type <code>!shortcut</code> in the editor to expand.
+ <span class="count">{{ allSnippets.length }} snippets</span>
+ </p>
</div>
+ </header>
- <TransitionGroup name="snippet" tag="div" class="snippets-grid">
- <!-- Existing snippets -->
- <div v-if="creatingSnippet" class="snippet-card editing">
- <div class="snippet-header">
- <div class="snippet-header-left"></div>
- <div class="snippet-actions">
- <button class="action-btn save-btn" title="Save snippet" @click="saveNewSnippet()">
- <Icon name="check" />
- </button>
- <button class="action-btn cancel-btn" title="Cancel creation" @click="cancelNewSnippet()">
- <Icon name="close" />
- </button>
- </div>
- </div>
- <div class="snippet-edit-form">
- <div class="form-group">
- <input v-model="newSnippet.id" class="snippet-key-input" placeholder="!shortcut" :class="{ error: error(newSnippet.id) }" />
- <div v-if="error(newSnippet.id)" class="error-message">{{ error(newSnippet.id) }}</div>
- </div>
- <div class="form-group">
- <label>Content:</label>
- <textarea
- v-model="newSnippet.label"
- class="snippet-content-input"
- placeholder="Snippet content...&#10;Use ${0}, ${1}, ... to tab through placeholders"
- rows="4"
- />
- </div>
- </div>
- </div>
- <div
- v-for="(snippet, index) in filteredSnippets"
- :key="snippet.id || index"
- class="snippet-card"
- :class="{ selected: selectedSnippets.includes(index), editing: editingIndex === index }"
- >
- <div class="snippet-header">
- <div class="snippet-header-left">
- <input type="checkbox" :checked="selectedSnippets.includes(index)" class="snippet-checkbox" @change="toggleSelection(index)" />
- <div v-if="editingIndex !== index" class="snippet-shortcut-display">
- <code class="shortcut-code">{{ snippet.id }}</code>
- </div>
- </div>
- <div class="snippet-actions">
- <button v-if="editingIndex !== index" class="action-btn edit-btn" title="Edit snippet" @click="startEdit(index)">
- <Icon name="edit" />
- </button>
- <button v-if="editingIndex === index" class="action-btn save-btn" title="Save snippet" @click="saveEdit()">
- <Icon name="check" />
- </button>
- <button v-if="editingIndex === index" class="action-btn cancel-btn" title="Cancel edit" @click="cancelEdit()">
- <Icon name="close" />
- </button>
- <button class="action-btn delete-btn" title="Delete snippet" @click="removeSnippet(index)">
- <Icon name="delete" />
- </button>
- </div>
- </div>
-
- <!-- Edit Mode -->
- <div v-if="editingIndex === index" class="snippet-edit-form">
- <div class="form-group">
- <label>Shortcut:</label>
- <input v-model="editingSnippet.id" class="snippet-key-input" placeholder="!shortcut" :class="{ error: error(editingSnippet.id) }" />
- <div v-if="error(editingSnippet.id)" class="error-message">{{ error(editingSnippet.id) }}</div>
- </div>
- <div class="form-group">
- <label>Content:</label>
- <textarea v-model="editingSnippet.label" class="snippet-content-input" placeholder="Snippet content..." rows="4" />
- </div>
+ <!-- Toolbar -->
+ <div class="toolbar">
+ <div class="dropdown-container">
+ <AppButton type="secondary" @click="showImportMenu = !showImportMenu"><Icon name="import" /> Import</AppButton>
+ <Transition name="fade">
+ <div v-if="showImportMenu" class="dropdown-menu">
+ <button @click="triggerImport('json')"><Icon name="backup" /> JSON file</button>
+ <button @click="triggerImport('dict')"><Icon name="import" /> Text dictionary</button>
</div>
+ </Transition>
+ <div v-if="showImportMenu" class="dropdown-backdrop" @click="showImportMenu = false" />
+ </div>
+ <AppButton type="secondary" @click="exportJSON"><Icon name="backup" /> Export</AppButton>
+ <AppButton type="secondary" @click="openRestoreModal"><Icon name="refresh" />Restore</AppButton>
+ <AppButton type="primary" @click="openModal('create')"><Icon name="plus" />New</AppButton>
+ </div>
- <!-- View Mode -->
- <div v-else class="snippet-content">
- <pre class="raw-content">{{ snippet.label }}</pre>
- </div>
+ <!-- Data Table -->
+ <DataTable v-if="allSnippets.length > 0" :headers="headers" :rows="rows">
+ <template #bulk-actions="{ selected }">
+ <div class="bulk-actions">
+ <span class="selected-count">{{ selected.length }}</span>
+ <span class="separator"></span>
+ <span class="action-btn" @click="bulkDelete(selected)"><Icon name="delete" fill="var(--font-color-light)" /></span>
</div>
-
- <!-- Temporary snippet creation -->
- </TransitionGroup>
- </div>
- <input ref="fileInput" type="file" accept=".json" style="display: none" @change="handleFileImport" />
+ </template>
+ <template #action="{ cell }">
+ <span class="action-btn" @click="openModal('edit', cell?.data as Snippet)"><Icon name="edit" /></span>
+ <span class="action-btn" @click="duplicateSnippet(cell?.data as Snippet)"><Icon name="copy" /></span>
+ <span class="action-btn" @click="handleDelete((cell?.data as Snippet).id)"><Icon name="delete" /></span>
+ </template>
+ </DataTable>
+
+ <!-- Empty State -->
+ <NoContent v-else title="No snippets yet">
+ <AppButton type="primary" @click="openModal('create')"><Icon name="plus" /> Create Snippet</AppButton>
+ </NoContent>
+
+ <!-- Hidden file inputs -->
+ <input ref="jsonInput" type="file" accept=".json" style="display: none" @change="handleJSONImport" />
+ <input ref="dictInput" type="file" accept=".txt,.dic,.csv" style="display: none" @change="handleDictImport" />
</div>
</template>
<script setup lang="ts">
-const preferences = usePreferences();
-
-const snippets = preferences.get('snippets');
-
-// Reactive state
-const searchQuery = ref('');
-const sortBy = ref('shortcut');
-const selectedSnippets = ref<number[]>([]);
-const editingIndex = ref<number | null>(null);
-const editingSnippet = ref<{ id: string; label: string }>({ id: '', label: '' });
-const originalSnippet = ref<{ id: string; label: string }>({ id: '', label: '' });
-
-const creatingSnippet = ref(false);
-const fileInput = ref<HTMLInputElement | null>(null);
-const newSnippet = ref<{ id: string; label: string }>({ id: '', label: '' });
-const sortOptions = [
- { id: 'shortcut', label: 'Sort by Shortcut' },
- { id: 'content', label: 'Sort by Content' },
- { id: 'usage', label: 'Sort by Usage' },
+import type { Snippet } from '~/composables/useSnippets';
+import type { Field } from '~/components/DataTable.vue';
+import SnippetModal from './_modals/SnippetModal.vue';
+import { Modal } from '~/composables/useModal';
+import RestoreModal from './_modals/Restore.vue';
+
+const { allSnippets, add, remove, update, exportJSON, importJSON, importDictionary, isDuplicate } = useSnippets();
+
+const notifications = useNotifications();
+const modalManager = useModal();
+
+// Table config
+const headers = [
+ { label: 'Shortcut', key: 'shortcut' },
+ { label: 'Content', key: 'content' },
+ { label: 'Actions', key: 'action', align: 'right' },
];
-const filteredSnippets = computed(() => {
- return snippets.value
- .filter(
- snippet => snippet.id.toLowerCase().includes(searchQuery.value.toLowerCase()) || snippet.label.toLowerCase().includes(searchQuery.value.toLowerCase()),
- )
- .sort((a, b) => a.id.localeCompare(b.id));
-});
-
-// Functions
-function addSnippet() {
- creatingSnippet.value = true;
- newSnippet.value = { id: '', label: '' };
-}
-
-function saveNewSnippet() {
- if (error(newSnippet.value.id)) return;
- snippets.value.unshift({ ...newSnippet.value });
- preferences.set('snippets', snippets.value);
- creatingSnippet.value = false;
- newSnippet.value = { id: '', label: '' };
-}
-
-function cancelNewSnippet() {
- creatingSnippet.value = false;
- newSnippet.value = { id: '', label: '' };
-}
-
-function removeSnippet(index: number) {
- const actualIndex = findActualIndex(index);
- if (actualIndex !== -1) {
- snippets.value.splice(actualIndex, 1);
-
- // Clear selection if deleted snippet was selected
- selectedSnippets.value = selectedSnippets.value.filter(i => i !== index);
- preferences.set('snippets', snippets.value);
- // Cancel editing if we're editing this snippet
- if (editingIndex.value === index) {
- cancelEdit();
- }
+const truncate = (str: string, len: number) => {
+ const oneLine = str.replace(/\n/g, ' ↵ ');
+ return oneLine.length > len ? oneLine.slice(0, len) + '…' : oneLine;
+};
+
+const rows = computed<Field[]>(() =>
+ allSnippets.value.map(snippet => ({
+ shortcut: { content: `<code class="snippet-code">${snippet.id}</code>`, type: 'html' },
+ content: { content: truncate(snippet.label, 80), type: 'text' },
+ action: { type: 'slot', data: snippet },
+ })),
+);
+
+// Modal
+const handleSave = (snippet: Snippet, originalId?: string): boolean => {
+ if (isDuplicate(snippet.id, originalId)) return false;
+ if (originalId) {
+ return update(originalId, snippet);
}
-}
-
-function findActualIndex(filteredIndex: number): number {
- const targetSnippet = filteredSnippets.value[filteredIndex];
- return snippets.value.findIndex(snippet => snippet.id === targetSnippet?.id && snippet.label === targetSnippet.label);
-}
-
-function toggleSelection(index: number) {
- const selectedIndex = selectedSnippets.value.indexOf(index);
- if (selectedIndex > -1) {
- selectedSnippets.value.splice(selectedIndex, 1);
- } else {
- selectedSnippets.value.push(index);
- }
-}
-
-function deleteSelected() {
- const actualIndices = selectedSnippets.value
- .map(findActualIndex)
- .filter(index => index !== -1)
- .sort((a, b) => b - a); // Sort in descending order to avoid index shifting
-
- actualIndices.forEach(index => {
- snippets.value.splice(index, 1);
- preferences.set('snippets', snippets.value);
+ return add(snippet);
+};
+
+const openModal = (mode: 'create' | 'edit', snippet?: Snippet) => {
+ modalManager.add(
+ new Modal(shallowRef(SnippetModal), {
+ size: 'small',
+ props: {
+ snippet: mode === 'edit' ? snippet : undefined,
+ onSave: handleSave,
+ },
+ }),
+ );
+};
+
+// Actions
+const handleDelete = (id: string) => {
+ remove(id);
+ notifications.add({ title: 'Snippet deleted', type: 'success' });
+};
+
+const bulkDelete = (selected: Field[]) => {
+ selected.forEach(row => {
+ const snippet = row.action?.data as Snippet;
+ if (snippet?.id) remove(snippet.id);
});
-
- selectedSnippets.value = [];
- cancelEdit();
-}
-
-function startEdit(index: number) {
- const actualIndex = findActualIndex(index);
- if (actualIndex !== -1) {
- editingIndex.value = index;
- editingSnippet.value = snippets.value[actualIndex]!;
- originalSnippet.value = snippets.value[actualIndex]!;
+ notifications.add({ title: `${selected.length} snippets deleted`, type: 'success' });
+};
+
+const openRestoreModal = () => {
+ modalManager.add(
+ new Modal(shallowRef(RestoreModal), {
+ size: 'small',
+ }),
+ );
+};
+
+const duplicateSnippet = (snippet: Snippet) => {
+ let newId = snippet.id + '_copy';
+ let counter = 1;
+ while (isDuplicate(newId)) {
+ newId = `${snippet.id}_copy${counter++}`;
}
-}
-
-function saveEdit() {
- if (editingIndex.value !== null && !error(editingSnippet.value.id)) {
- const actualIndex = findActualIndex(editingIndex.value);
- if (actualIndex !== -1) {
- snippets.value[actualIndex] = { ...editingSnippet.value };
- preferences.set('snippets', snippets.value);
- }
- cancelEdit();
+ add({ id: newId, label: snippet.label });
+};
+
+// Import
+const showImportMenu = ref(false);
+const jsonInput = ref<HTMLInputElement>();
+const dictInput = ref<HTMLInputElement>();
+
+const triggerImport = (type: 'json' | 'dict') => {
+ showImportMenu.value = false;
+ if (type === 'json') {
+ jsonInput.value?.click();
+ } else {
+ dictInput.value?.click();
}
-}
-
-function cancelEdit() {
- editingIndex.value = null;
- editingSnippet.value = { id: '', label: '' };
- originalSnippet.value = { id: '', label: '' };
-}
+};
-function error(shortcut: string): string | false {
- // Return This shortcut already exists if duplicate
- const isDuplicate = snippets.value.some((snippet, index) => {
- const actualIndex = findActualIndex(index);
- return snippet.id === shortcut && actualIndex !== findActualIndex(editingIndex.value ?? -1);
- });
- if (isDuplicate) {
- return 'This shortcut already exists.';
+const handleJSONImport = async (e: Event) => {
+ const file = (e.target as HTMLInputElement).files?.[0];
+ if (!file) return;
+ try {
+ const count = await importJSON(file);
+ notifications.add({ title: `Imported ${count} snippets`, type: 'success' });
+ } catch {
+ notifications.add({ title: 'Failed to import JSON', type: 'error' });
}
- return false;
-}
-
-function exportSnippets() {
- const dataStr = JSON.stringify(snippets.value, null, 2);
- const dataBlob = new Blob([dataStr], { type: 'application/json' });
- const url = URL.createObjectURL(dataBlob);
+ (e.target as HTMLInputElement).value = '';
+};
- const link = document.createElement('a');
- link.href = url;
- link.download = 'alexandrie-snippets.json';
- document.body.appendChild(link);
- link.click();
- document.body.removeChild(link);
-
- URL.revokeObjectURL(url);
-}
-
-function importSnippets() {
- fileInput.value?.click();
-}
-
-function handleFileImport(event: Event) {
- const file = (event.target as HTMLInputElement)?.files?.[0];
+const handleDictImport = async (e: Event) => {
+ const file = (e.target as HTMLInputElement).files?.[0];
if (!file) return;
-
- const reader = new FileReader();
- reader.onload = e => {
- try {
- const importedSnippets = JSON.parse(e.target?.result as string);
- if (Array.isArray(importedSnippets)) {
- // Merge with existing snippets, avoiding duplicates
- const existingIds = new Set(snippets.value.map(s => s.id));
- const newSnippets = importedSnippets.filter(snippet => snippet.id && snippet.label && !existingIds.has(snippet.id));
-
- snippets.value = [...snippets.value, ...newSnippets];
- }
- } catch {
- useNotifications().add({ title: 'Failed to import snippets. Please check the file format.', type: 'error' });
- }
- };
-
- reader.readAsText(file);
-
- // Reset input
- if (fileInput.value) {
- fileInput.value.value = '';
+ try {
+ const count = await importDictionary(file);
+ notifications.add({ title: `Imported ${count} words`, type: 'success' });
+ } catch {
+ notifications.add({ title: 'Failed to import dictionary', type: 'error' });
}
-}
-
-function restoreDefaults() {
- snippets.value = [...DEFAULT_PREFERENCES.snippets];
- selectedSnippets.value = [];
- cancelEdit();
-}
-
-// Watch for search query changes to clear selection
-watch(searchQuery, () => {
- selectedSnippets.value = [];
-});
+ (e.target as HTMLInputElement).value = '';
+};
</script>
<style scoped lang="scss">
-// Header styles
-.header {
- margin-bottom: 2rem;
-}
-
-// Toolbar styles
-.toolbar {
- gap: 1rem;
- margin-bottom: 2rem;
+.snippets-page {
+ width: 100%;
}
-.search-section {
- display: flex;
- align-items: center;
- flex: 1;
- gap: 1rem;
+// Header
+.page-header {
+ margin-bottom: 1.5rem;
- @media (width <= 768px) {
- align-items: stretch;
+ .header-content {
+ display: flex;
flex-direction: column;
+ gap: 0.25rem;
}
-}
-.search-wrapper {
- position: relative;
- max-width: 400px;
- flex: 1;
-
- @media (width <= 768px) {
- max-width: none;
+ .count {
+ margin-left: 0.5rem;
+ padding: 0.15rem 0.5rem;
+ border-radius: 999px;
+ font-size: 0.75rem;
+ color: var(--font-color-light);
+ background: var(--bg-ui);
}
-}
-.search-icon {
- position: absolute;
- top: 50%;
- left: 0.75rem;
- font-size: 1rem;
- transform: translateY(-50%);
-}
-
-.search-input {
- width: 100%;
- color: var(--font-color);
- background: var(--bg-color);
- padding-left: 2.5rem;
+ code {
+ padding: 0.1rem 0.4rem;
+ border-radius: 4px;
+ font-size: 0.85em;
+ background: var(--code-bg);
+ }
}
-.filter-section {
+// Toolbar
+.toolbar {
display: flex;
- gap: 0.5rem;
-}
-
-// Snippets container
-.snippets-container {
- min-height: 200px;
- border-radius: 12px;
- background-color: var(--bg-ui);
+ flex-wrap: wrap;
+ gap: 4px;
+ margin-bottom: 1rem;
}
-.no-snippets {
- display: flex;
- padding: 4rem 2rem;
- align-items: center;
- justify-content: center;
-
- .no-snippets-icon {
- font-size: 3rem;
- opacity: 0.5;
- }
-
- p {
- margin: 0;
- }
+.dropdown-container {
+ position: relative;
}
-// Grid layout
-.snippets-grid {
- display: grid;
- gap: 0.5rem;
- grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
-
- @media (width <= 768px) {
- gap: 1rem;
- grid-template-columns: 1fr;
- }
+.dropdown-backdrop {
+ position: fixed;
+ top: 0;
+ right: 0;
+ bottom: 0;
+ left: 0;
+ z-index: 99;
}
-// Snippet card
-.snippet-card {
- position: relative;
- padding: 0.5rem 1rem;
+.dropdown-menu {
+ position: absolute;
+ top: 100%;
+ left: 0;
+ z-index: 100;
+ min-width: 160px;
+ margin-top: 0.25rem;
+ padding: 0.25rem;
+ border: 1px solid var(--border-color);
border-radius: 8px;
- transition: all 0.2s ease;
-
- &:hover {
- background-color: var(--bg-ui);
- }
-
- &.selected {
- border-color: var(--primary);
- background: var(--primary-bg-light);
- }
-
- &.editing {
- border-color: var(--green);
+ background: var(--bg-color);
+ box-shadow: 0 4px 12px rgb(0 0 0 / 15%);
+
+ button {
+ display: flex;
+ width: 100%;
+ gap: 0.5rem;
+ padding: 0.5rem 0.75rem;
+ border: none;
+ border-radius: 6px;
+ font-size: 0.85rem;
+ text-align: left;
+ color: var(--font-color);
+ background: none;
+ align-items: center;
+ cursor: pointer;
+
+ &:hover {
+ background: var(--bg-ui);
+ }
}
}
-// Card header
-.snippet-header {
+// Bulk actions
+.bulk-actions {
display: flex;
align-items: center;
- justify-content: space-between;
+ gap: 8px;
}
-.snippet-header-left {
+.selected-count {
display: flex;
+ width: 32px;
+ height: 36px;
+ padding: 6px;
+ border: 1px solid var(--border-color);
+ border-radius: 4px;
+ font-size: 13px;
+ font-weight: bold;
+ color: var(--font-color-light);
align-items: center;
- gap: 0.75rem;
-}
-
-.snippet-checkbox {
- width: 17px;
- height: 17px;
- cursor: pointer;
-}
-
-.snippet-shortcut-display {
- .shortcut-code {
- font-family: $monospace-font;
- font-size: 0.9rem;
- font-weight: 600;
- color: var(--font-color-dark);
- background: var(--code-bg);
- }
+ justify-content: center;
}
-.snippet-actions {
- display: flex;
- gap: 0.25rem;
+.separator {
+ height: 32px;
+ margin-left: 4px;
+ border-left: 1px solid var(--border-color);
}
.action-btn {
- display: flex;
- min-width: 32px;
- height: 32px;
- padding: 0.4rem;
- border: none;
- border-radius: 6px;
- font-size: 0.9rem;
- background: transparent;
- transition: background-color 0.2s ease;
- align-items: center;
+ margin-right: 10px;
cursor: pointer;
- justify-content: center;
&:hover {
- background: var(--bg-ui);
+ opacity: 0.7;
}
}
-// Edit form
-.snippet-edit-form {
- .form-group {
- margin-bottom: 1rem;
-
- .snippet-key-input,
- .snippet-content-input {
- width: 100%;
- padding: 0.75rem;
- border: 1px solid var(--border-color);
- border-radius: 6px;
- font-family: $monospace-font;
- font-size: 0.9rem;
- text-align: left;
- transition: border-color 0.2s ease;
- resize: vertical;
-
- &:focus {
- border-color: var(--primary);
- box-shadow: 0 0 0 2px var(--primary-border);
- outline: none;
- }
-
- &.error {
- border-color: var(--red);
- box-shadow: 0 0 0 2px var(--red-border);
- }
- }
-
- .error-message {
- font-size: 0.85rem;
- color: var(--red);
- margin-top: 0.5rem;
- }
- }
-}
-
-// View mode content
-.snippet-content {
- .raw-label {
- font-size: 0.85rem;
- font-weight: 600;
- }
-
- .raw-content {
- margin: 0;
- font-family: $monospace-font;
- line-height: 1.4;
- background: var(--code-bg);
- white-space: nowrap;
- }
+// Code styling for table
+:deep(.snippet-code) {
+ padding: 0.2rem 0.5rem;
+ border-radius: 4px;
+ font-family: $monospace-font;
+ font-size: 0.85rem;
+ font-weight: 500;
+ color: var(--primary);
+ background: var(--code-bg);
}
// Transitions
-.snippet-enter-active,
-.snippet-leave-active {
- transition: all 0.3s ease;
-}
-
-.snippet-enter-from {
- opacity: 0;
- transform: translateY(20px) scale(0.95);
+.fade-enter-active,
+.fade-leave-active {
+ transition: opacity 0.15s ease;
}
-.snippet-leave-to {
+.fade-enter-from,
+.fade-leave-to {
opacity: 0;
- transform: translateY(-20px) scale(0.95);
-}
-
-.snippet-move {
- transition: transform 0.3s ease;
}
</style>
diff --git a/frontend/public/app-icons/refresh.svg b/frontend/public/app-icons/refresh.svg
new file mode 100644
index 00000000..25c2785d
--- /dev/null
+++ b/frontend/public/app-icons/refresh.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960"><path d="M480-160q-134 0-227-93t-93-227q0-134 93-227t227-93q69 0 132 28.5T720-690v-110h80v280H520v-80h168q-32-56-87.5-88T480-720q-100 0-170 70t-70 170q0 100 70 170t170 70q77 0 139-44t87-116h84q-28 106-114 173t-196 67Z"/></svg>
\ No newline at end of file