Skip to content

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

feat(sql-editor): SQL editor sharing feature part Ⅲ (#595)

Yunwei Xiao7e53dc1885b8
diff --git a/frontend/src/components/MonacoEditor/MonacoEditor.vue b/frontend/src/components/MonacoEditor/MonacoEditor.vue
index 31f0bd0f87..b3463f164d 100644
--- a/frontend/src/components/MonacoEditor/MonacoEditor.vue
+++ b/frontend/src/components/MonacoEditor/MonacoEditor.vue
@@ -15,6 +15,8 @@ import {
onUnmounted,
watch,
} from "vue";
+import { useStore } from "vuex";
+import { useI18n } from "vue-i18n";
import type { editor as Editor } from "monaco-editor";
import { useMonaco } from "./useMonaco";
@@ -23,6 +25,7 @@ import {
SqlDialect,
SqlEditorActions,
SqlEditorState,
+ SheetGetters,
} from "../../types";
import {
useNamespacedActions,
@@ -53,10 +56,15 @@ const editorRef = ref();
const sqlCode = toRef(props, "value");
const language = toRef(props, "language");
+const store = useStore();
+const { t } = useI18n();
const { shouldSetContent } = useNamespacedState<SqlEditorState>("sqlEditor", [
"shouldSetContent",
]);
const { currentTab } = useNamespacedGetters<TabGetters>("tab", ["currentTab"]);
+const { isReadOnly } = useNamespacedGetters<SheetGetters>("sheet", [
+ "isReadOnly",
+]);
const { setShouldSetContent } = useNamespacedActions<SqlEditorActions>(
"sqlEditor",
["setShouldSetContent"]
@@ -121,6 +129,14 @@ const init = async () => {
contextMenuGroupId: "operation",
contextMenuOrder: 1,
run: () => {
+ if (isReadOnly.value) {
+ store.dispatch("notification/pushNotification", {
+ module: "bytebase",
+ style: "INFO",
+ title: t("sql-editor.notify.sheet-is-read-only"),
+ });
+ return;
+ }
formatContent(editorInstance, language.value);
nextTick(() => setPositionAtEndOfLine(editorInstance));
},
@@ -148,6 +164,19 @@ const init = async () => {
const value = editorInstance.getValue();
emit("save", value);
});
+
+ watch(
+ () => isReadOnly.value,
+ (readOnly) => {
+ if (editorInstance) {
+ editorInstance.updateOptions({ readOnly });
+ }
+ },
+ {
+ deep: true,
+ immediate: true,
+ }
+ );
};
onMounted(init);
diff --git a/frontend/src/locales/en.yml b/frontend/src/locales/en.yml
index 56cea92c85..3beda65401 100644
--- a/frontend/src/locales/en.yml
+++ b/frontend/src/locales/en.yml
@@ -167,6 +167,8 @@ common:
delete: Delete
history: History
loading: Loading
+ copy: Copy
+ copied: Copied
error-page:
go-back-home: Go back home
anomaly-center: Anomaly Center
@@ -1110,10 +1112,20 @@ sql-editor:
copy-code: Copy code
notify:
copy-code-succeed: Copy code succeed
+ copy-share-link: The share link was copied to Clipboard.
+ sheet-is-read-only: The shared sheet is read-only.
view-all-tabs: View all Tabs
sheet: Sheet
sheets: Sheets
connection-holder: Select a connection or select a sheet from left panel to get started
+ link-access: Link access
+ private: Private
+ private-desc: Only you can access this sheet
+ project-desc: >-
+ Both sheet OWNER and project OWNER can read/write, and project DEVELOPER can
+ read
+ public: Public
+ public-desc: Sheet OWNER can read/write, and all others can read
label:
empty-label-value: <Empty Value>
no-label: No labels
diff --git a/frontend/src/locales/zh-CN.yml b/frontend/src/locales/zh-CN.yml
index edb4107908..f109dc6a45 100644
--- a/frontend/src/locales/zh-CN.yml
+++ b/frontend/src/locales/zh-CN.yml
@@ -167,6 +167,8 @@ common:
delete: 删除
history: 历史记录
loading: 加载中
+ copied: 已拷贝
+ copy: 拷贝
error-page:
go-back-home: 回到主页
anomaly-center: 异常中心
@@ -981,10 +983,18 @@ sql-editor:
copy-code: 复制代码
notify:
copy-code-succeed: 代码复制成功
+ copy-share-link: 分享链接已拷贝到剪贴板
+ sheet-is-read-only: 分享的工作表是只读的,无法编辑。
view-all-tabs: 查看所有标签页
sheet: 工作表
sheets: 工作表
connection-holder: 选择一个数据连接或者从左侧面板选择一个工作表以开始
+ link-access: 链接访问权限
+ private: 私有
+ private-desc: 只有您自己可以访问此工作表
+ project-desc: 工作表所有者或者项目所有者拥有读、写权限,项目开发者拥有只读权限
+ public: 公开
+ public-desc: 工作表所有者拥有读写权限,其他人只拥有只读权限.
label:
empty-label-value: <空值>
no-label: 没有标签
diff --git a/frontend/src/plugins/naive-ui.ts b/frontend/src/plugins/naive-ui.ts
index 3e2c0acd1d..b42f4551f4 100644
--- a/frontend/src/plugins/naive-ui.ts
+++ b/frontend/src/plugins/naive-ui.ts
@@ -8,6 +8,8 @@ import {
NDataTable,
NDropdown,
NInput,
+ NInputGroup,
+ NInputGroupLabel,
NMessageProvider,
NModal,
NPopover,
@@ -32,6 +34,8 @@ const naive = create({
NDataTable,
NDropdown,
NInput,
+ NInputGroup,
+ NInputGroupLabel,
NMessageProvider,
NModal,
NPopover,
diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts
index 9447960adf..f1ecde4476 100644
--- a/frontend/src/router/index.ts
+++ b/frontend/src/router/index.ts
@@ -13,7 +13,7 @@ import SplashLayout from "../layouts/SplashLayout.vue";
import SqlEditorLayout from "../layouts/SqlEditorLayout.vue";
import { t } from "../plugins/i18n";
import { store } from "../store";
-import { Database, QuickActionType } from "../types";
+import { Database, QuickActionType, Sheet } from "../types";
import { idFromSlug, isDBAOrOwner, isOwner } from "../utils";
// import PasswordReset from "../views/auth/PasswordReset.vue";
import Signin from "../views/auth/Signin.vue";
@@ -779,6 +779,13 @@ const routes: Array<RouteRecordRaw> = [
component: () => import("../views/SqlEditor/SqlEditor.vue"),
props: true,
},
+ {
+ path: "/sql-editor/:connectionSlug/:sheetSlug",
+ name: "sql-editor.share",
+ meta: { title: () => "SQL Editor" },
+ component: () => import("../views/SqlEditor/SqlEditor.vue"),
+ props: true,
+ },
],
},
];
@@ -931,6 +938,7 @@ router.beforeEach((to, from, next) => {
const migrationHistorySlug = routerSlug.migrationHistorySlug;
const vcsSlug = routerSlug.vcsSlug;
const connectionSlug = routerSlug.connectionSlug;
+ const sheetSlug = routerSlug.sheetSlug;
if (principalId) {
store
@@ -1134,6 +1142,34 @@ router.beforeEach((to, from, next) => {
databaseId: Number(databaseId),
})
.then(() => {
+ // for sharing the sheet to others
+ if (sheetSlug) {
+ const [_, sheetId] = sheetSlug.split("_");
+ store
+ .dispatch("sheet/fetchSheetById", sheetId)
+ .then((sheet: Sheet) => {
+ store.dispatch("tab/addTab", {
+ name: sheet.name,
+ statement: sheet.statement,
+ isSaved: true,
+ });
+ store.dispatch("tab/updateCurrentTab", {
+ sheetId: sheet.id,
+ });
+ store.dispatch("sqlEditor/setSqlEditorState", {
+ sharedSheet: sheet,
+ });
+
+ next();
+ })
+ .catch((error) => {
+ next({
+ name: "error.404",
+ replace: false,
+ });
+ throw error;
+ });
+ }
next();
})
.catch((error) => {
diff --git a/frontend/src/store/modules/router.ts b/frontend/src/store/modules/router.ts
index cf595d3519..07a3bf2f62 100644
--- a/frontend/src/store/modules/router.ts
+++ b/frontend/src/store/modules/router.ts
@@ -162,6 +162,21 @@ const getters = {
}
}
+ {
+ // /sql-editor/:connectionSlug/:sheetSlug
+ // match this route first
+ const sqlEditorComponents = currentRoute.path.match(
+ "/sql-editor/([0-9a-zA-Z_-]+)/([0-9a-zA-Z_-]+)"
+ ) || ["/", undefined, undefined];
+
+ if (sqlEditorComponents[1] && sqlEditorComponents[2]) {
+ return {
+ connectionSlug: sqlEditorComponents[1],
+ sheetSlug: sqlEditorComponents[2],
+ };
+ }
+ }
+
{
// /sql-editor/:connectionSlug
const sqlEditorComponents = currentRoute.path.match(
diff --git a/frontend/src/store/modules/sheet.ts b/frontend/src/store/modules/sheet.ts
index 28b5647e4a..e7bfe00c2c 100644
--- a/frontend/src/store/modules/sheet.ts
+++ b/frontend/src/store/modules/sheet.ts
@@ -16,6 +16,8 @@ import type {
TabInfo,
Instance,
Database,
+ Project,
+ ProjectMember,
} from "../../types";
import { unknown } from "../../types";
import { getPrincipalFromIncludedList } from "./principal";
@@ -35,6 +37,12 @@ function convertSheet(
let database: Database = unknown("DATABASE") as Database;
+ const projectId = rootGetters["sqlEditor/findProjectIdByDatabaseId"](
+ Number(databaseId)
+ );
+
+ let project: Project = unknown("PROJECT") as Project;
+
for (const item of includedList || []) {
if (item.type == "instance" && item.id == instanceId) {
instance = rootGetters["instance/convert"](item, includedList);
@@ -42,10 +50,14 @@ function convertSheet(
if (item.type == "database" && item.id == databaseId) {
database = rootGetters["database/convert"](item, includedList);
}
+ if (item.type == "project" && Number(item.id) === Number(projectId)) {
+ project = rootGetters["project/convert"](item, includedList);
+ }
}
return {
...(sheet.attributes as Omit<Sheet, "id" | "creator" | "updater">),
+ id: parseInt(sheet.id),
creator: getPrincipalFromIncludedList(
sheet.relationships!.creator.data,
includedList
@@ -56,7 +68,7 @@ function convertSheet(
) as Principal,
instance,
database,
- id: parseInt(sheet.id),
+ project,
};
}
@@ -82,6 +94,63 @@ const getters = {
return state.sheetById.get(sheetId) || (unknown("SHEET") as Sheet);
},
+ isCreator: (
+ state: SheetState,
+ getters: any,
+ rootState: any,
+ rootGetters: any
+ ) => {
+ const currentUser = rootGetters["auth/currentUser"]();
+ const currentSheet = getters.currentSheet;
+
+ if (!currentSheet) return false;
+
+ return currentUser.id === currentSheet!.creator.id;
+ },
+ /**
+ * Check the sheet whether is read-only.
+ * 1、If the sheet is not created yet, it can not be edited.
+ * 2、If the sheet is created by the current user, it can be edited.
+ * 3、If the sheet is created by other user, will be checked the visibility of the sheet.
+ * a) If the sheet's visibility is private or public, it can be edited only if the current user is the creator of the sheet.
+ * b) If the sheet's visibility is project, will be checked whether the current user is the `OWNER` of the project, only the current user is the `OWNER` of the project, it can be edited.
+ */
+ isReadOnly: (
+ state: SheetState,
+ getters: any,
+ rootState: any,
+ rootGetters: any
+ ) => {
+ const currentUser = rootGetters["auth/currentUser"]();
+ const currentSheet = getters.currentSheet;
+
+ if (!currentSheet) return true;
+ // creator always can edit
+ if (getters.isCreator) return false;
+
+ const isPrivate = currentSheet?.visibility === "PRIVATE" ?? false;
+ const isProject = currentSheet?.visibility === "PROJECT" ?? false;
+ const isPublic = currentSheet?.visibility === "PUBLIC" ?? false;
+
+ const isCurrentUserProjectOwner = () => {
+ const projectMemberList = currentSheet?.project.memberList;
+
+ if (projectMemberList && projectMemberList.length > 0) {
+ const currentMemberByProjectMember = projectMemberList?.find(
+ (member: ProjectMember) => {
+ return member.principal.id === currentUser.id;
+ }
+ );
+
+ return currentMemberByProjectMember.role !== "OWNER";
+ }
+
+ return false;
+ };
+
+ // if current user is not creator, check the link access level by project relationship
+ return isPrivate || isPublic || (isProject && isCurrentUserProjectOwner());
+ },
};
const mutations = {
@@ -172,6 +241,19 @@ const actions = {
sheetList.sort((a, b) => b.createdTs - a.createdTs)
);
},
+ async fetchSheetById(
+ { commit, dispatch, state, rootGetters }: any,
+ sheetId: SheetId
+ ) {
+ const data = (await axios.get(`/api/sheet/${sheetId}`)).data;
+ const sheet = convertSheet(data.data, data.included, rootGetters);
+ commit(types.SET_SHEET_BY_ID, {
+ sheetId: sheet.id,
+ sheet: sheet,
+ });
+
+ return sheet;
+ },
// update
async patchSheetById(
{ dispatch, rootGetters }: any,
diff --git a/frontend/src/store/modules/sqlEditor.ts b/frontend/src/store/modules/sqlEditor.ts
index 601477dbe6..0bf682829f 100644
--- a/frontend/src/store/modules/sqlEditor.ts
+++ b/frontend/src/store/modules/sqlEditor.ts
@@ -6,17 +6,22 @@ import {
ConnectionAtom,
QueryInfo,
ConnectionContext,
+ Instance,
Database,
DatabaseId,
ProjectId,
QueryHistory,
UNKNOWN_ID,
+ Sheet,
} from "../../types";
import * as types from "../mutation-types";
import { makeActions } from "../actions";
+import { unknown } from "../../types";
export const getDefaultConnectionContext = () => ({
hasSlug: false,
+ projectId: UNKNOWN_ID,
+ projectName: "",
instanceId: UNKNOWN_ID,
instanceName: "",
databaseId: UNKNOWN_ID,
@@ -38,6 +43,7 @@ const state: () => SqlEditorState = () => ({
queryHistoryList: [],
isFetchingQueryHistory: false,
isFetchingSheet: false,
+ sharedSheet: unknown("SHEET") as Sheet,
});
const getters = {
@@ -92,11 +98,11 @@ const getters = {
};
},
findProjectIdByDatabaseId:
- (state: SqlEditorState, getter: any) =>
+ (state: SqlEditorState, getter: any, rootState: any) =>
(databaseId: DatabaseId): ProjectId => {
- let projectId = 1;
+ let projectId = UNKNOWN_ID;
const databaseListByProjectId =
- getter.connectionInfo.databaseListByProjectId;
+ rootState.database.databaseListByProjectId;
for (const [id, databaseList] of databaseListByProjectId) {
const idx = databaseList.findIndex(
(database: Database) => database.id === databaseId
@@ -204,16 +210,16 @@ const actions = {
{ commit, dispatch }: any,
{ instanceId, databaseId }: Partial<SqlEditorState["connectionContext"]>
) {
- const instanceInfo = await dispatch(
+ const instanceInfo = (await dispatch(
"instance/fetchInstanceById",
instanceId,
{ root: true }
- );
- const databaseInfo = await dispatch(
+ )) as Instance;
+ const databaseInfo = (await dispatch(
"database/fetchDatabaseById",
{ databaseId },
{ root: true }
- );
+ )) as Database;
commit(types.SET_CONNECTION_CONTEXT, {
hasSlug: true,
instanceId,
diff --git a/frontend/src/types/common.ts b/frontend/src/types/common.ts
index 94129786f0..5e617b1cc7 100644
--- a/frontend/src/types/common.ts
+++ b/frontend/src/types/common.ts
@@ -67,6 +67,7 @@ export type RouterSlug = {
migrationHistorySlug?: string;
vcsSlug?: string;
connectionSlug?: string;
+ sheetSlug?: string;
};
// Quick Action Type
diff --git a/frontend/src/types/sheet.ts b/frontend/src/types/sheet.ts
index 859a28e9aa..b1f8ef5e18 100644
--- a/frontend/src/types/sheet.ts
+++ b/frontend/src/types/sheet.ts
@@ -5,6 +5,7 @@ import {
Database,
DatabaseId,
Principal,
+ Project,
} from ".";
export type SheetVisibility = "PRIVATE" | "PROJECT" | "PUBLIC";
@@ -23,6 +24,7 @@ export interface Sheet {
instance: Instance;
databaseId?: DatabaseId;
database?: Database;
+ project?: Project;
// Domain fields
name: string;
@@ -39,6 +41,10 @@ export type SheetPatch = Partial<
Pick<Sheet, "id" | "name" | "statement" | "visibility">
>;
+export type SheetFind = Partial<
+ Pick<Sheet, "databaseId" | "instanceId" | "visibility">
+>;
+
export type AccessOption = {
label: string;
description: string;
diff --git a/frontend/src/types/store.ts b/frontend/src/types/store.ts
index f0942bd42e..fc8ac15b7a 100644
--- a/frontend/src/types/store.ts
+++ b/frontend/src/types/store.ts
@@ -201,6 +201,7 @@ export interface SqlEditorState {
isExecuting: boolean;
isFetchingSheet: boolean;
isShowExecutingHint: boolean;
+ sharedSheet: Sheet;
}
export type SqlEditorGetters = typeof sqlEditorStore.getters;
export type SqlEditorActions = typeof sqlEditorStore.actions;
diff --git a/frontend/src/views/SqlEditor/AsidePanel/SheetContainer.vue b/frontend/src/views/SqlEditor/AsidePanel/SheetContainer.vue
index a37be4df84..8f269120aa 100644
--- a/frontend/src/views/SqlEditor/AsidePanel/SheetContainer.vue
+++ b/frontend/src/views/SqlEditor/AsidePanel/SheetContainer.vue
@@ -111,6 +111,7 @@ import {
Sheet,
SqlEditorActions,
SqlEditorState,
+ UNKNOWN_ID,
} from "../../../types";
import { getHighlightHTMLByKeyWords } from "../../../utils";
import DeleteHint from "./DeleteHint.vue";
@@ -127,10 +128,11 @@ interface State {
const { t } = useI18n();
const { setConnectionContextFromCurrentTab } = useSQLEditorConnection();
-const { isFetchingSheet: isLoading } = useNamespacedState<SqlEditorState>(
- "sqlEditor",
- ["isFetchingSheet"]
-);
+const { sharedSheet, isFetchingSheet: isLoading } =
+ useNamespacedState<SqlEditorState>("sqlEditor", [
+ "sharedSheet",
+ "isFetchingSheet",
+ ]);
const { sheetList } = useNamespacedState<SheetState>("sheet", ["sheetList"]);
const { tabList } = useNamespacedState<TabState>("tab", ["tabList"]);
const { currentTab } = useNamespacedGetters<TabGetters>("tab", ["currentTab"]);
@@ -162,9 +164,13 @@ const state = reactive<State>({
const queryNameInputerRef = ref<HTMLInputElement>();
const data = computed(() => {
+ const newSheetList =
+ sharedSheet.value.id !== UNKNOWN_ID
+ ? [...sheetList.value, sharedSheet.value]
+ : sheetList.value;
const tempData =
- sheetList.value && sheetList.value.length > 0
- ? sheetList.value.filter((sheet) => {
+ newSheetList && newSheetList.length > 0
+ ? newSheetList.filter((sheet) => {
let t = false;
if (sheet.name.includes(state.search)) {
diff --git a/frontend/src/views/SqlEditor/EditorPanel/EditorAction.vue b/frontend/src/views/SqlEditor/EditorPanel/EditorAction.vue
index a337b87846..7e7fc00b81 100644
--- a/frontend/src/views/SqlEditor/EditorPanel/EditorAction.vue
+++ b/frontend/src/views/SqlEditor/EditorPanel/EditorAction.vue
@@ -30,9 +30,22 @@
>
<carbon:save class="h-5 w-5" /> &nbsp; {{ $t("common.save") }} (⌘+S)
</NButton>
- <NButton v-if="isDev()" :disabled="isEmptyStatement">
- <carbon:share class="h-5 w-5" /> &nbsp; {{ $t("common.share") }} (⌘+S)
- </NButton>
+ <NPopover
+ trigger="click"
+ placement="bottom-end"
+ :show-arrow="false"
+ :show="isShowSharePopover"
+ >
+ <template #trigger>
+ <NButton
+ :disabled="isEmptyStatement || isDisconnected"
+ @click="isShowSharePopover = !isShowSharePopover"
+ >
+ <carbon:share class="h-5 w-5" /> &nbsp; {{ $t("common.share") }}
+ </NButton>
+ </template>
+ <SharePopover @close="isShowSharePopover = false" />
+ </NPopover>
</div>
</div>
</template>
@@ -58,7 +71,7 @@ import {
UNKNOWN_ID,
} from "../../../types";
import { useExecuteSQL } from "../../../composables/useExecuteSQL";
-import { isDev } from "../../../utils";
+import SharePopover from "./SharePopover.vue";
const { connectionTree, connectionContext } =
useNamespacedState<SqlEditorState>("sqlEditor", [
@@ -87,6 +100,7 @@ const { updateCurrentTab } = useNamespacedActions<TabActions>("tab", [
const selectedConnection = ref();
const isSeletedDatabase = ref(false);
+const isShowSharePopover = ref(false);
const isEmptyStatement = computed(
() => !currentTab.value || currentTab.value.statement === ""
);
diff --git a/frontend/src/views/SqlEditor/EditorPanel/SharePopover.vue b/frontend/src/views/SqlEditor/EditorPanel/SharePopover.vue
new file mode 100644
index 0000000000..f12c6ab4b2
--- /dev/null
+++ b/frontend/src/views/SqlEditor/EditorPanel/SharePopover.vue
@@ -0,0 +1,203 @@
+<template>
+ <div class="share-popover w-112 p-2 space-y-4">
+ <section class="flex justify-between">
+ <div class="pr-4">
+ <h2 class="text-lg font-semibold">{{ $t("common.share") }}</h2>
+ </div>
+ <NPopover trigger="click" :show="isShowAccessPopover">
+ <template #trigger>
+ <div
+ class="flex items-center cursor-pointer"
+ @click="isShowAccessPopover = !isShowAccessPopover"
+ >
+ <span class="pr-2">{{ $t("sql-editor.link-access") }}:</span>
+ <strong>{{ currentAccess.label }}</strong>
+ <heroicons-solid:chevron-down />
+ </div>
+ </template>
+ <div class="access-content space-y-2 w-80">
+ <div
+ v-for="(option, idx) in accessOptions"
+ :key="option.label"
+ class="p-2 rounded-sm flex justify-between"
+ :class="[
+ creatorAccessStyle,
+ {
+ 'bg-accent text-white': option.value === currentAccess.value,
+ },
+ ]"
+ @click="handleChangeAccess(option)"
+ >
+ <div class="access-content--prefix flex">
+ <div v-if="idx === 0" class="mt-1">
+ <heroicons-outline:user class="h-5 w-5" />
+ </div>
+ <div v-if="idx === 1" class="mt-1">
+ <heroicons-outline:user-group class="h-5 w-5" />
+ </div>
+ <div v-if="idx === 2" class="mt-1">
+ <heroicons-outline:globe class="h-5 w-5" />
+ </div>
+ <section class="flex flex-col pl-2">
+ <h2 class="text-md flex">
+ {{ option.label }}
+ </h2>
+ <h3 class="text-xs" :class="creatorAccessDescStyle">
+ {{ option.description }}
+ </h3>
+ </section>
+ </div>
+ <div
+ v-show="option.value === currentAccess.value"
+ class="access-content--suffix flex items-center"
+ >
+ <heroicons-solid:check class="h-5 w-5" />
+ </div>
+ </div>
+ </div>
+ </NPopover>
+ </section>
+ <NInputGroup class="flex items-center justify-center">
+ <n-input-group-label class="flex items-center">
+ <heroicons-solid:link class="h-4 w-4" />
+ </n-input-group-label>
+ <n-input v-model:value="sharedTabLink" disabled />
+ <NButton
+ class="w-20"
+ :type="copied ? 'success' : 'primary'"
+ @click="handleCopy"
+ >
+ <heroicons-solid:check v-if="copied" class="h-4 w-4" />
+ {{ copied ? $t("common.copied") : $t("common.copy") }}
+ </NButton>
+ </NInputGroup>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { ref, computed, onMounted, defineEmits } from "vue";
+import { useClipboard } from "@vueuse/core";
+import { useStore } from "vuex";
+import { useI18n } from "vue-i18n";
+import {
+ useNamespacedGetters,
+ useNamespacedState,
+ useNamespacedActions,
+} from "vuex-composition-helpers";
+import slug from "slug";
+
+import {
+ TabGetters,
+ SqlEditorState,
+ SheetGetters,
+ SheetActions,
+ AccessOption,
+} from "../../../types";
+
+const emit = defineEmits<{
+ (e: "close"): void;
+}>();
+
+const store = useStore();
+const { t } = useI18n();
+
+const accessOptions = computed<AccessOption[]>(() => {
+ return [
+ {
+ label: t("sql-editor.private"),
+ value: "PRIVATE",
+ description: t("sql-editor.private-desc"),
+ },
+ {
+ label: t("common.project"),
+ value: "PROJECT",
+ description: t("sql-editor.project-desc"),
+ },
+ {
+ label: t("sql-editor.public"),
+ value: "PUBLIC",
+ description: t("sql-editor.public-desc"),
+ },
+ ];
+});
+
+const { connectionContext } = useNamespacedState<SqlEditorState>("sqlEditor", [
+ "connectionContext",
+]);
+const { currentTab } = useNamespacedGetters<TabGetters>("tab", ["currentTab"]);
+const { currentSheet, isCreator } = useNamespacedGetters<SheetGetters>(
+ "sheet",
+ ["currentSheet", "isCreator"]
+);
+const { patchSheetById } = useNamespacedActions<SheetActions>("sheet", [
+ "patchSheetById",
+]);
+
+const ctx = connectionContext.value;
+
+const host = window.location.host;
+const connectionSlug = [
+ slug(ctx.instanceName as string),
+ ctx.instanceId,
+ slug(ctx.databaseName as string),
+ ctx.databaseId,
+].join("_");
+
+const currentAccess = ref<AccessOption>(accessOptions.value[0]);
+const isShowAccessPopover = ref(false);
+
+const creatorAccessStyle = computed(() => {
+ return isCreator.value
+ ? "cursor-pointer hover:bg-accent hover:text-white"
+ : "bg-transparent text-gray-300 cursor-not-allowed";
+});
+const creatorAccessDescStyle = computed(() => {
+ return isCreator.value ? "text-gray-400" : "text-gray-300 cursor-not-allowed";
+});
+
+const updateSheet = () => {
+ if (currentTab.value.sheetId) {
+ patchSheetById({
+ id: currentTab.value.sheetId,
+ visibility: currentAccess.value.value,
+ });
+ }
+};
+
+const handleChangeAccess = (option: AccessOption) => {
+ // only creator can change access
+ if (isCreator.value) {
+ currentAccess.value = option;
+ updateSheet();
+ }
+ isShowAccessPopover.value = false;
+};
+
+const sheetSlug = `${slug(currentTab.value.name)}_${currentTab.value.sheetId}`;
+const sharedTabLink = ref(`${host}/sql-editor/${connectionSlug}/${sheetSlug}`);
+
+const { copy, copied } = useClipboard({
+ source: sharedTabLink.value,
+});
+
+const handleCopy = async () => {
+ await copy();
+ store.dispatch("notification/pushNotification", {
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("sql-editor.notify.copy-share-link"),
+ });
+ emit("close");
+};
+
+onMounted(() => {
+ if (currentSheet.value) {
+ const { visibility } = currentSheet.value;
+ const idx = accessOptions.value.findIndex(
+ (item) => item.value === visibility
+ );
+ currentAccess.value =
+ idx !== -1 ? accessOptions.value[idx] : accessOptions.value[0];
+ }
+});
+</script>