123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509 |
- <script setup lang="ts">
- import { ref, onMounted, computed, nextTick, onUnmounted, provide } from "vue";
- import _ from "lodash";
- import { v4 as uuid4 } from "uuid";
- import {
- S3Client,
- PutObjectCommand,
- ListObjectsCommand,
- GetObjectCommand,
- DeleteObjectsCommand,
- CopyObjectCommand,
- } from "@aws-sdk/client-s3";
- import { Plus, Refresh } from "@element-plus/icons-vue";
- import Node from "./Node.vue";
- import AppendModal from "./AppendModal.vue";
- import type { TreeData } from "./Tree";
- import { ElNotification, type ElTree } from "element-plus";
- import { MdEditor } from "md-editor-v3";
- import { s3ContentsToTree, getTreeFlatten } from "@/utils/s3Helper";
- import type ETNode from "element-plus/es/components/tree/src/model/node";
- import type { DragEvents } from "element-plus/es/components/tree/src/model/useDragNode";
- import type {
- AllowDropType,
- NodeDropType,
- } from "element-plus/es/components/tree/src/tree.type";
- import VideoToolBarItem from './VideoToolBarItem.vue'
- import path from "path-browserify";
- const s3 = new S3Client({
- credentials: {
- accessKeyId: import.meta.env.VITE_AWS_S3_ACCESS_KEY_ID,
- secretAccessKey: import.meta.env.VITE_AWS_S3_SECRET_ACCESS_KEY,
- },
- region: import.meta.env.VITE_AWS_S3_REGION,
- });
- provide('s3', s3)
- const SIDEBAR_SORTED_MAP_KEY = "SIDEBAR_SORTED_MAP.json";
- const tree$ = ref<InstanceType<typeof ElTree>>();
- const editor$ = ref<InstanceType<typeof MdEditor>>();
- const langSelect = ref<"zh-CN" | "zh-HK" | "en-US">("zh-CN");
- const langKeyPrefix = computed(() => {
- return {
- "zh-CN": "docs/",
- "zh-HK": "zh-HK/docs/",
- "en-US": "en-US/docs/",
- }[langSelect.value];
- });
- const langDataSource = ref<
- Partial<Record<"zh-CN" | "zh-HK" | "en-US", TreeData[]>>
- >({});
- const langSelectedDataSource = computed(() => {
- return langDataSource.value[langSelect.value];
- });
- const dataSource = ref<unknown[]>([]);
- const sideLoading = ref(false);
- const loadS3DocsListObjects = async () => {
- const command = new ListObjectsCommand({
- Bucket: import.meta.env.VITE_DOCS_LIST_BUCKET,
- });
- const result = await s3.send(command);
- return result.Contents!;
- };
- const loadS3SideBarSort = async (lang) => {
- try {
- const command = new GetObjectCommand({
- Bucket: import.meta.env.VITE_DOCS_LIST_BUCKET,
- Key: `${lang}::${SIDEBAR_SORTED_MAP_KEY}`,
- ResponseCacheControl: "no-cache",
- });
- const file = await s3.send(command);
- return JSON.parse(await file.Body?.transformToString()!);
- } catch (e) {
- console.warn(e);
- }
- return {};
- };
- const loadSideBar = async () => {
- sideLoading.value = true;
- dataSource.value = await loadS3DocsListObjects();
- const allLangs: ("zh-CN" | "zh-HK" | "en-US")[] = ["zh-CN", "zh-HK", "en-US"];
- await Promise.all(
- allLangs.map(async (lang: "zh-CN" | "zh-HK" | "en-US") => {
- const prefix = {
- "zh-CN": "docs/",
- "zh-HK": "zh-HK/docs/",
- "en-US": "en-US/docs/",
- }[lang];
- const sideBarSortMap = await loadS3SideBarSort(lang);
- const filtered = dataSource.value
- .filter((cont) => cont.Key.startsWith(prefix))
- .map((cont) => ({
- ...cont,
- Key: cont.Key.replace(new RegExp(`^${prefix}`), ""),
- }))
- .sort((a, b) => sideBarSortMap[a.Key] - sideBarSortMap[b.Key]);
- // TODO sort
- langDataSource.value[lang] = s3ContentsToTree(
- filtered,
- {},
- (r, label, i, a, thisContent) => ({
- isDir: a.length !== i + 1,
- ...(a.length === i + 1 ? thisContent : {}),
- })
- );
- })
- );
- sideLoading.value = false;
- };
- onMounted(() => {
- loadSideBar();
- });
- const currentOpenData = ref<TreeData>();
- const onNodeClick = async (data: TreeData, node) => {
- if (data.isDir) {
- return;
- }
- textLoading.value = true;
- const command = new GetObjectCommand({
- Bucket: import.meta.env.VITE_DOCS_LIST_BUCKET,
- Key: `${langKeyPrefix.value}${data.key}`,
- ResponseCacheControl: "no-cache",
- });
- const file = await s3.send(command);
- text.value = await file.Body?.transformToString()!;
- currentOpenData.value = data;
- textLoading.value = false;
- };
- const text = ref("");
- const textLoading = ref(false);
- provide('editorLoading', textLoading)
- const onUploadImg = async (
- files: File[],
- callback: (
- urls: string[] | { url: string; alt: string; title: string }[]
- ) => void
- ) => {
- let result = [];
- for (const file of files) {
- try {
- const key = `${uuid4()}::${file.name}`;
- const command = new PutObjectCommand({
- Bucket: import.meta.env.VITE_DOCS_MEDIA_BUCKET,
- Key: key,
- Body: file,
- ACL: "public-read",
- });
- const res = await s3.send(command);
- result.push({
- url: `https://${
- import.meta.env.VITE_DOCS_MEDIA_BUCKET
- }.s3.amazonaws.com/${key}`,
- alt: file.name,
- title: file.name,
- });
- } catch (e) {
- console.error(e);
- ElNotification.error(`${file.name} 上传失败`);
- }
- }
- callback(result);
- };
- const onSave = async () => {
- if (!currentOpenData.value) {
- ElNotification.info("请先选择文件");
- return;
- }
- textLoading.value = true;
- try {
- const command = new PutObjectCommand({
- Bucket: import.meta.env.VITE_DOCS_LIST_BUCKET,
- Key: `${langKeyPrefix.value}${currentOpenData.value?.key}`,
- Body: text.value,
- });
- await s3.send(command);
- ElNotification.success(`${currentOpenData.value?.key} 保存成功`);
- } catch (e) {
- console.error(e);
- ElNotification.error(`${currentOpenData.value?.key} 保存失败`);
- } finally {
- textLoading.value = false;
- }
- };
- let resolveAppend: Function | undefined;
- let rejectAppend: Function | undefined;
- const showAppendModal = ref(false);
- const appendLoading = ref(false);
- const appendContextData = ref();
- const onAppend = async (data: TreeData) => {
- const modalConfirmPromise = new Promise((resolve, reject) => {
- resolveAppend = resolve;
- rejectAppend = reject;
- });
- appendContextData.value = data;
- showAppendModal.value = true;
- let filename, isDir;
- try {
- ({ filename, isDir } = await modalConfirmPromise);
- } catch (e) {
- return;
- }
- try {
- appendLoading.value = true;
- // const key = `${langKeyPrefix.value}${data.key ? `${data.key}/` : ''}${filename}`
- const key = path.join(langKeyPrefix.value, data.key ?? "", filename);
- if (!isDir) {
- const command = new PutObjectCommand({
- Bucket: import.meta.env.VITE_DOCS_LIST_BUCKET,
- Key: key,
- Body: "",
- });
- await s3.send(command);
- }
- const newChild: TreeData = {
- key: `${data.key ? `${data.key}/` : ""}${filename}`,
- label: filename,
- children: [],
- isDir,
- };
- if (!data.children) {
- data.children = [];
- }
- data.children.push(newChild);
- } catch (e) {
- console.error(e);
- ElNotification.error("添加失败");
- } finally {
- appendLoading.value = false;
- showAppendModal.value = false;
- }
- if (!isDir) {
- saveSideBarSort();
- }
- };
- const onRemove = async (node: ETNode, data: TreeData) => {
- const parent = node.parent;
- const children = parent.data.children || parent.data;
- const index = children.findIndex((d) => d.key === data.key);
- sideLoading.value = true;
- try {
- const leafDatas = getTreeFlatten(data);
- const command = new DeleteObjectsCommand({
- Bucket: import.meta.env.VITE_DOCS_LIST_BUCKET,
- Delete: {
- Objects: leafDatas.map((d) => ({
- Key: `${langKeyPrefix.value}${d.key}`,
- })),
- Quiet: false,
- },
- });
- await s3.send(command);
- children.splice(index, 1);
- } catch (e) {
- console.error(e);
- ElNotification.error("删除失败");
- } finally {
- sideLoading.value = false;
- }
- };
- const saveSideBarSort = async () => {
- sideLoading.value = true;
- const sortedNodes = getTreeFlatten(
- { children: tree$.value!.data } as TreeData,
- "preorder",
- "all"
- );
- const sortedKeyMap = sortedNodes.reduce(
- (a, v, i) => ({ ...a, [path.join(...v.__path__!)]: i }),
- {}
- );
- const command = new PutObjectCommand({
- Bucket: import.meta.env.VITE_DOCS_LIST_BUCKET,
- Key: `${langSelect.value}::${SIDEBAR_SORTED_MAP_KEY}`,
- Body: JSON.stringify(sortedKeyMap),
- });
- await s3.send(command);
- sideLoading.value = false;
- };
- const onDragEnd = async (
- draggingNode: ETNode,
- dropNode: ETNode,
- dropType: NodeDropType,
- ev: DragEvents
- ) => {
- if (dropType === "none") {
- return;
- }
- sideLoading.value = true;
- const copySourceNodes = getTreeFlatten(draggingNode.data);
- const waitForDelete = [];
- for (const sourceNode of copySourceNodes) {
- if (sourceNode.isDir) {
- continue;
- }
- const copySource = path.join(langKeyPrefix.value, sourceNode.key);
- const copyTarget = path.join(
- langKeyPrefix.value,
- dropType === "inner" ? dropNode.data.key : dropNode.parent.data.key ?? "",
- path.basename(draggingNode.data.key),
- path.relative(draggingNode.data.key, sourceNode.key)
- );
- if (copySource === copyTarget) {
- continue;
- }
- try {
- const command = new CopyObjectCommand({
- Bucket: import.meta.env.VITE_DOCS_LIST_BUCKET,
- CopySource: encodeURIComponent(
- `/${import.meta.env.VITE_DOCS_LIST_BUCKET}/${copySource}`
- ),
- Key: copyTarget,
- });
- await s3.send(command);
- waitForDelete.push({ Key: copySource });
- } catch (e) {
- console.error(e);
- console.warn(`${copySource} 复制失败`);
- }
- }
- if (waitForDelete.length) {
- const command = new DeleteObjectsCommand({
- Bucket: import.meta.env.VITE_DOCS_LIST_BUCKET,
- Delete: {
- Objects: waitForDelete,
- Quiet: false,
- },
- });
- await s3.send(command);
- }
- sideLoading.value = false;
- nextTick(async () => {
- await saveSideBarSort();
- await loadSideBar();
- });
- };
- const allowDrop = (draggingNode: Node, dropNode: Node, type: AllowDropType) => {
- return !(!dropNode.data.isDir && type === "inner");
- };
- let observer: InstanceType<typeof MutationObserver>
- const callback = (mutationList: MutationRecord[]) => {
- const preview$ = ( mutationList.at(-1)?.target as HTMLElement ).querySelector('#helpdocs-editor-preview')
- preview$?.classList.remove('md-editor-preview')
- };
- onMounted(() => {
- const el = document.querySelector('#helpdocs-editor')
- if (el) {
- observer = new MutationObserver(callback)
- observer.observe(el, { childList: true, subtree: true })
- }
- })
- onUnmounted(() => {
- observer && observer.disconnect()
- })
- </script>
- <template>
- <div class="md-container">
- <div class="left" v-loading="sideLoading">
- <div class="toolbar">
- <el-segmented
- v-model="langSelect"
- :options="[
- { label: '简体中文', value: 'zh-CN' },
- { label: '繁体中文', value: 'zh-HK' },
- { label: 'English', value: 'en-US' },
- ]"
- />
- <el-button-group>
- <el-button
- @click="onAppend({ key: '', label: '', children: langSelectedDataSource })"
- type="primary"
- text
- :icon="Plus"
- >
- </el-button>
- <el-button @click="loadSideBar" type="info" text :icon="Refresh"></el-button>
- </el-button-group>
- </div>
- <el-divider />
- <el-tree
- ref="tree$"
- :data="langSelectedDataSource"
- node-key="key"
- default-expand-all
- :expand-on-click-node="false"
- @node-click="onNodeClick"
- draggable
- :allow-drop="allowDrop"
- @node-drag-end="onDragEnd"
- >
- <template #default="{ node, data }">
- <Node
- :node="node"
- :data="data"
- @append="() => onAppend(data)"
- @remove="() => onRemove(node, data)"
- />
- </template>
- </el-tree>
- </div>
- <MdEditor
- ref="editor$"
- editorId="helpdocs-editor"
- v-model="text"
- v-loading="textLoading"
- :disabled="!currentOpenData"
- :toolbars="[
- 'bold',
- 'underline',
- 'italic',
- 'strikeThrough',
- '-',
- 'title',
- 'sub',
- 'sup',
- 'quote',
- 'unorderedList',
- 'orderedList',
- 'task',
- '-',
- 'codeRow',
- 'code',
- 'link',
- 'image',
- 0,
- 'table',
- 'mermaid',
- 'katex',
- '-',
- 'revoke',
- 'next',
- 'save',
- '=',
- 'prettier',
- 'pageFullscreen',
- 'fullscreen',
- 'preview',
- 'previewOnly',
- 'htmlPreview',
- 'catalog',
- ]"
- previewTheme="custom"
- class="vp-doc"
- @save="onSave"
- @uploadImg="onUploadImg"
- >
- <template #defToolbars>
- <VideoToolBarItem />
- </template>
- </MdEditor>
- </div>
- <AppendModal
- v-model:show="showAppendModal"
- :contextData="appendContextData"
- :appendLoading="appendLoading"
- @ok="(formData) => resolveAppend?.(formData)"
- @cancel="() => rejectAppend?.()"
- />
- </template>
- <style src="md-editor-v3/lib/style.css"></style>
- <style lang="scss" scoped>
- .md-container {
- width: 100vw;
- height: 100dvh;
- display: flex;
- align-items: stretch;
- .md-editor {
- flex: 1;
- height: 100%;
- }
- .left {
- flex: 0 0 300px;
- padding: 10px;
- display: flex;
- flex-direction: column;
- align-items: stretch;
- .toolbar {
- display: flex;
- flex-direction: column;
- gap: 5px;
- }
- .el-tree {
- overflow: auto;
- flex: 1;
- :deep(.el-tree-node.is-current) {
- & > .el-tree-node__content {
- background-color: aqua;
- }
- }
- }
- }
- }
- </style>
|