Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat(sql-editor): persistent tab list (#2907)

Liu Jiafc58a54bead
diff --git a/frontend/src/components/ProvideSQLEditorContext.vue b/frontend/src/components/ProvideSQLEditorContext.vue
index 10e7e2b9c9..c4caff3c14 100644
--- a/frontend/src/components/ProvideSQLEditorContext.vue
+++ b/frontend/src/components/ProvideSQLEditorContext.vue
@@ -16,7 +16,7 @@ import {
useInstanceStore,
pushNotification,
} from "@/store";
-import type { Instance, Database, ConnectionAtom } from "@/types";
+import type { Instance, Database, Connection, ConnectionAtom } from "@/types";
import { ConnectionTreeState, UNKNOWN_ID, DEFAULT_PROJECT_ID } from "@/types";
import {
emptyConnection,
@@ -25,6 +25,8 @@ import {
sheetSlug as makeSheetSlug,
connectionSlug as makeConnectionSlug,
isSheetReadable,
+ isSameConnection,
+ isTempTab,
} from "@/utils";
import { useI18n } from "vue-i18n";
@@ -122,18 +124,18 @@ const prepareSheet = async () => {
} else {
// Open the sheet in a "temp" tab otherwise.
tabStore.selectOrAddTempTab();
+ tabStore.updateCurrentTab({
+ sheetId: sheet.id,
+ name: sheet.name,
+ statement: sheet.statement,
+ isSaved: true,
+ connection: {
+ ...emptyConnection(),
+ instanceId: sheet.database?.instanceId || UNKNOWN_ID,
+ databaseId: sheet.databaseId || UNKNOWN_ID,
+ },
+ });
}
- tabStore.updateCurrentTab({
- sheetId: sheet.id,
- name: sheet.name,
- statement: sheet.statement,
- isSaved: true,
- connection: {
- ...emptyConnection(),
- instanceId: sheet.database?.instanceId || UNKNOWN_ID,
- databaseId: sheet.databaseId || UNKNOWN_ID,
- },
- });
return true;
};
@@ -148,12 +150,31 @@ const prepareConnectionSlug = async () => {
return false;
}
- tabStore.selectOrAddTempTab();
+ const maybeOpenNewTab = (connection: Connection) => {
+ const tab = tabStore.currentTab;
+ if (tab.sheetId) {
+ // Don't touch a saved sheet.
+ tabStore.selectOrAddTempTab();
+ return;
+ }
+ if (isTempTab(tab)) {
+ // Override current tab if it's a temp tab.
+ return;
+ }
+ if (isSameConnection(tab.connection, connection)) {
+ // Stay on current tab if its connection and target connection are equal.
+ return;
+ }
+ // Select or add a temp tab otherwise.
+ tabStore.selectOrAddTempTab();
+ };
+
if (Number.isNaN(databaseId)) {
// connected to instance
const connection = await sqlEditorStore.fetchConnectionByInstanceId(
instanceId
);
+ maybeOpenNewTab(connection);
tabStore.updateCurrentTab({ connection });
} else {
// connected to db
@@ -162,6 +183,7 @@ const prepareConnectionSlug = async () => {
instanceId,
databaseId
);
+ maybeOpenNewTab(connection);
tabStore.updateCurrentTab({ connection });
}
return true;
@@ -241,8 +263,11 @@ onMounted(async () => {
watch(currentUser, (user) => {
if (user.id === UNKNOWN_ID) {
+ // Cleanup when user signed out
sqlEditorStore.connectionTree.data = [];
sqlEditorStore.connectionTree.state = ConnectionTreeState.UNSET;
+
+ tabStore.reset();
}
});
diff --git a/frontend/src/store/modules/tab.ts b/frontend/src/store/modules/tab.ts
index 01fecc1454..d353e65a15 100644
--- a/frontend/src/store/modules/tab.ts
+++ b/frontend/src/store/modules/tab.ts
@@ -1,18 +1,54 @@
import { defineStore } from "pinia";
-import { computed, ref } from "vue";
+import { computed, reactive, ref, watch } from "vue";
+import { pick } from "lodash-es";
+import { watchThrottled } from "@vueuse/core";
import type { TabInfo, AnyTabInfo } from "@/types";
import { UNKNOWN_ID } from "@/types";
-import { getDefaultTab, INITIAL_TAB, isTempTab } from "@/utils";
+import {
+ getDefaultTab,
+ INITIAL_TAB,
+ isTempTab,
+ WebStorageHelper,
+} from "@/utils";
import { useInstanceStore } from "./instance";
+import { useSheetStore } from "./sheet";
+
+const LOCAL_STORAGE_KEY_PREFIX = "bb.sql-editor.tab-list";
+const KEYS = {
+ tabIdList: "tab-id-list",
+ currentTabId: "current-tab-id",
+ tab: (id: string) => `tab.${id}`,
+};
+
+// Only store the core fields of a tab.
+// Don't store anything which might be too large.
+const PERSISTENT_TASK_FIELDS = [
+ "id",
+ "name",
+ "connection",
+ "isSaved",
+ "savedAt",
+ "statement",
+ "sheetId",
+] as const;
+type PersistentTaskInfo = Pick<TabInfo, typeof PERSISTENT_TASK_FIELDS[number]>;
export const useTabStore = defineStore("tab", () => {
+ const storage = new WebStorageHelper("bb.sql-editor.tab-list", localStorage);
const instanceStore = useInstanceStore();
// states
- const tabList = ref<TabInfo[]>([INITIAL_TAB]);
- const currentTabId = ref(INITIAL_TAB.id);
+ // We store the tabIdList and the tabs separately.
+ // This index-entity modeling enables us to update one tab entity at a time,
+ // and reduce the performance costing while writing localStorage.
+ const tabs = ref(new Map<string, TabInfo>());
+ const tabIdList = ref<string[]>([]);
+ const currentTabId = ref<string>();
// getters
+ const tabList = computed((): TabInfo[] =>
+ tabIdList.value.map((id) => tabs.value.get(id) ?? getDefaultTab())
+ );
const currentTab = computed((): TabInfo => {
const tab = tabList.value.find((tab) => tab.id === currentTabId.value);
return tab ?? getDefaultTab();
@@ -32,20 +68,25 @@ export const useTabStore = defineStore("tab", () => {
// actions
const addTab = (payload?: AnyTabInfo) => {
- const defaultTab = getDefaultTab();
-
- const newTab = {
- ...defaultTab,
+ const newTab = reactive<TabInfo>({
+ ...getDefaultTab(),
...payload,
- };
+ });
+
+ const { id } = newTab;
+ tabIdList.value.push(id);
+ currentTabId.value = id;
+ tabs.value.set(id, newTab);
- currentTabId.value = newTab.id;
- tabList.value.push(newTab);
+ watchTab(newTab, false);
};
- const removeTab = (payload: TabInfo) => {
- const index = tabList.value.indexOf(payload);
+ const removeTab = (tab: TabInfo) => {
+ const id = tab.id;
+ const index = tabIdList.value.indexOf(id);
if (index >= 0) {
- tabList.value.splice(index, 1);
+ tabIdList.value.splice(index, 1);
+ tabs.value.delete(id);
+ storage.remove(KEYS.tab(id));
}
};
const updateCurrentTab = (payload: AnyTabInfo) => {
@@ -55,6 +96,9 @@ export const useTabStore = defineStore("tab", () => {
currentTabId.value = id;
};
const selectOrAddTempTab = () => {
+ if (isTempTab(currentTab.value)) {
+ return;
+ }
const tempTab = tabList.value.find(isTempTab);
if (tempTab) {
setCurrentTabId(tempTab.id);
@@ -62,9 +106,98 @@ export const useTabStore = defineStore("tab", () => {
addTab();
}
};
+ const _cleanup = (tabIdList: string[]) => {
+ const prefix = `${LOCAL_STORAGE_KEY_PREFIX}.tab.`;
+ const keys = storage.keys().filter((key) => key.startsWith(prefix));
+ keys.forEach((key) => {
+ const id = key.substring(prefix.length);
+ if (tabIdList.indexOf(id) < 0) {
+ storage.remove(KEYS.tab(id));
+ }
+ });
+ };
+
+ // watchers
+ const watchTab = (tab: TabInfo, immediate: boolean) => {
+ // Use a throttled watcher to reduce the performance overhead when writing.
+ watchThrottled(
+ () => pick(tab, ...PERSISTENT_TASK_FIELDS),
+ (tabPartial: PersistentTaskInfo) => {
+ storage.save(KEYS.tab(tabPartial.id), tabPartial);
+ },
+ { deep: true, immediate, throttle: 100, trailing: true }
+ );
+ };
+
+ // Load session from local storage.
+ // Reset if failed.
+ const init = () => {
+ // Load tabIdList and currentTabId
+ tabIdList.value = storage.load(KEYS.tabIdList, []);
+ currentTabId.value = storage.load(KEYS.currentTabId, INITIAL_TAB.id);
+ if (tabIdList.value.length === 0) {
+ // tabIdList is empty accidentally
+ tabIdList.value = [INITIAL_TAB.id];
+ }
+ if (tabIdList.value.indexOf(currentTabId.value) < 0) {
+ // currentTabId is not in tabIdList accidentally
+ // fallback to the first tab
+ currentTabId.value = tabIdList.value[0];
+ }
+
+ // Load tab details
+ tabIdList.value.forEach((id) => {
+ const tabPartial = storage.load<PersistentTaskInfo | undefined>(
+ KEYS.tab(id),
+ undefined
+ );
+ // Use a stored tab info if possible.
+ // Fallback to getDefaultTab() otherwise.
+ const tab = reactive<TabInfo>({
+ ...getDefaultTab(),
+ ...tabPartial,
+ id,
+ });
+ watchTab(tab, false);
+ tabs.value.set(id, tab);
+ });
+
+ // Fetch opening sheets if needed
+ const sheetStore = useSheetStore();
+ tabList.value.forEach((tab) => {
+ if (tab.sheetId) {
+ sheetStore.getOrFetchSheetById(tab.sheetId);
+ }
+ });
+
+ // Clean up unused stored tabs
+ _cleanup(tabIdList.value);
+
+ watch(
+ currentTabId,
+ (id) => {
+ storage.save(KEYS.currentTabId, id);
+ },
+ { immediate: true }
+ );
+ watch(
+ tabIdList,
+ (idList) => {
+ storage.save(KEYS.tabIdList, idList);
+ },
+ { deep: true, immediate: true }
+ );
+ };
+ init();
+
+ const reset = () => {
+ storage.clear();
+ init();
+ };
// exposure
return {
+ tabIdList,
tabList,
currentTabId,
currentTab,
@@ -74,5 +207,6 @@ export const useTabStore = defineStore("tab", () => {
updateCurrentTab,
setCurrentTabId,
selectOrAddTempTab,
+ reset,
};
});
diff --git a/frontend/src/utils/index.ts b/frontend/src/utils/index.ts
index e525a2beca..7f15bede42 100644
--- a/frontend/src/utils/index.ts
+++ b/frontend/src/utils/index.ts
@@ -19,4 +19,5 @@ export * from "./principal";
export * from "./sql-editor";
export * from "./sheet";
export * from "./pev2";
+export * from "./web-storage";
export * from "./dom";
diff --git a/frontend/src/utils/web-storage.ts b/frontend/src/utils/web-storage.ts
new file mode 100644
index 0000000000..b79d823190
--- /dev/null
+++ b/frontend/src/utils/web-storage.ts
@@ -0,0 +1,57 @@
+export class WebStorageHelper {
+ storage: Storage;
+ keyPrefix: string;
+
+ constructor(keyPrefix: string, storage = localStorage) {
+ this.keyPrefix = keyPrefix;
+ this.storage = storage;
+ }
+
+ save<T>(key: string, value: T) {
+ const fullKey = `${this.keyPrefix}.${key}`;
+ try {
+ const json = JSON.stringify(value);
+ localStorage.setItem(fullKey, json);
+ } catch {
+ // nothing
+ }
+ }
+
+ load<T>(key: string, fallbackValue: T) {
+ const fullKey = `${this.keyPrefix}.${key}`;
+ try {
+ const json = localStorage.getItem(fullKey) || "";
+ return JSON.parse(json) as T;
+ } catch {
+ return fallbackValue;
+ }
+ }
+
+ remove(key: string) {
+ const fullKey = `${this.keyPrefix}.${key}`;
+ try {
+ localStorage.removeItem(fullKey);
+ } catch {
+ // nothing
+ }
+ }
+
+ keys(): string[] {
+ const { length } = localStorage;
+ const keys: string[] = [];
+ for (let i = 0; i < length; i++) {
+ const key = localStorage.key(i);
+ if (key && key.startsWith(this.keyPrefix)) {
+ keys.push(key);
+ }
+ }
+ return keys;
+ }
+
+ clear() {
+ const keys = this.keys();
+ keys.forEach((key) => {
+ localStorage.removeItem(key);
+ });
+ }
+}
diff --git a/frontend/src/views/sql-editor/TabListContainer.vue b/frontend/src/views/sql-editor/TabListContainer.vue
index 714151aa85..d1e4e19407 100644
--- a/frontend/src/views/sql-editor/TabListContainer.vue
+++ b/frontend/src/views/sql-editor/TabListContainer.vue
@@ -17,8 +17,8 @@
:class="{ active: tab.id === tabStore.currentTabId }"
:style="scrollState.style"
@click="handleSelectTab(tab)"
- @mouseover="enterTabId = tab.id"
- @mouseleave="enterTabId = ''"
+ @mouseover="hoverTabId = tab.id"
+ @mouseleave="hoverTabId = ''"
>
<div
class="label max-w-5xl w-48 truncate"
@@ -54,7 +54,7 @@
<span :class="isTempTab(tab) && 'italic'">{{ tab.name }}</span>
</span>
</div>
- <template v-if="enterTabId === tab.id && tabStore.tabList.length > 1">
+ <template v-if="hoverTabId === tab.id && tabStore.tabList.length > 1">
<span
class="suffix close hover:bg-gray-200 rounded-sm"
@click.prevent.stop="handleRemoveTab(tab)"
@@ -95,7 +95,7 @@
</div>
<div class="tab-list-more">
<NPopselect
- v-model:value="selectedTab"
+ v-model:value="tabStore.currentTabId"
:options="localTabList"
trigger="click"
size="medium"
@@ -116,7 +116,7 @@
</template>
<script lang="ts" setup>
-import { ref, reactive, nextTick, computed, onMounted, onUnmounted } from "vue";
+import { ref, reactive, nextTick, computed } from "vue";
import { debounce } from "lodash-es";
import { useI18n } from "vue-i18n";
import { useDialog } from "naive-ui";
@@ -130,8 +130,7 @@ const sheetStore = useSheetStore();
const { t } = useI18n();
const dialog = useDialog();
-const enterTabId = ref("");
-const selectedTab = computed(() => tabStore.currentTabId);
+const hoverTabId = ref("");
// edit label state
const labelState = reactive({
currentLabelName: "",
@@ -276,17 +275,6 @@ const handleScollTabList = debounce((e: WheelEvent) => {
console.log(e.deltaX > 0 ? "Move to right" : "Move to left");
console.log(e.offsetX);
}, 333);
-
-// add listener to confirm confrim if close the tab.
-onMounted(() => {
- window.onbeforeunload = () => {
- return "false";
- };
-});
-// remove if unmount view
-onUnmounted(() => {
- window.onbeforeunload = null;
-});
</script>
<style scoped>