Bläddra i källkod

复制组件时,设置和背景丢失问题

dsy 1 månad sedan
förälder
incheckning
4f454ddb5f

+ 11 - 0
packages/BookEep.vue

@@ -171,6 +171,10 @@ export default {
       type: String,
       default: '{}',
     },
+    changeChapter: {
+      type: Function,
+      default: () => {},
+    },
   },
   data() {
     const isMobile = /android|iphone|ipad|ipod|openharmony|harmonyos/i.test(
@@ -767,6 +771,13 @@ export default {
       const cw = this.getActiveCoursewareComponent();
       return JSON.stringify((cw && cw.rowCheckList) || {});
     },
+    /**
+     * @description 选择章节节点
+     * @param {string} id - 章节节点 ID
+     */
+    selectChapterNode(id) {
+      this.changeChapter(id);
+    },
   },
 };
 </script>

+ 9 - 3
src/views/book/courseware/create/components/CreateCanvas.vue

@@ -1958,12 +1958,18 @@ export default {
     },
     /**
      * @description 粘贴组件
-     * @param {Object} componentData 组件数据
+     * @param {Object} componentData 复制的组件数据(含组件内容与组件背景)
      * @param {String} position 放入位置类型
      */
     pasteComponent(componentData, position) {
       if (!componentData) return;
-      let _data = JSON.parse(JSON.stringify(componentData));
+      // 兼容只传组件内容的复制数据
+      const isClipboardData =
+        typeof componentData === 'object' && 'data' in componentData && 'background' in componentData;
+      const copyData = isClipboardData ? componentData.data : componentData;
+      const background = isClipboardData ? componentData.background || '' : '';
+      if (!copyData) return;
+      let _data = JSON.parse(JSON.stringify(copyData));
       const curId = this.getCurSettingId();
       const attrs = this.findChildComponentByKey(`grid-${curId}`)?.$attrs;
       if (!attrs) return;
@@ -2028,7 +2034,7 @@ export default {
       }
       this.$nextTick(() => {
         let newComponent = this.findChildComponentByKey(`grid-${id}`); // 获取新添加的组件实例
-        newComponent?.setData(_data); // 设置新添加的组件数据
+        newComponent?.setData(_data, background); // 设置新添加的组件数据与背景
       });
     },
     // 交换组件位置

+ 105 - 39
src/views/book/courseware/create/components/common/ModuleMixin.js

@@ -9,6 +9,8 @@ import { displayList, viewMethodList, isEnable, analysisData, answerData } from
 import {
   ContentSaveCoursewareComponentContent,
   ContentGetCoursewareComponentContent,
+  GetCoursewareComponentBackground,
+  SaveCoursewareComponentBackground,
   PinyinBuild_OldFormat,
 } from '@/api/book';
 
@@ -57,6 +59,7 @@ const mixin = {
       property: {
         isGetContent: false, // 是否已获取内容
         isSilentPropertyWatch: false, // 初始化组件内容时,临时静默 property 监听
+        isDataPreset: false, // 组件内容是否已由外部预设(粘贴组件),预设后不再用初始化数据覆盖
       },
       borderColorObj: Vue.observable({ value: this.borderColor }), // 边框颜色
       multilingualVisible: false, // 多语言弹窗
@@ -158,47 +161,50 @@ const mixin = {
 
       ContentGetCoursewareComponentContent({ courseware_id: coursewareID, component_id })
         .then(({ content }) => {
-          if (content) {
-            let oldData = {};
-            try {
-              oldData = JSON.parse(content) ?? {};
-            } catch (error) {
-              // 内容不是合法 JSON 时不能让组件停留在空数据上
-              console.error('组件内容解析失败,已使用默认内容', error);
-            }
-            if (oldData.type === 'audio') {
-              let p = oldData.property || {};
-              if (!p.file_name_display_mode) p.file_name_display_mode = 'true';
-              if (p.view_method === 'independent' && !p.style_mode) {
-                p.style_mode = 'middle';
+          // 粘贴组件时内容已由源组件预设,接口返回的初始内容(通常为空)不能覆盖粘贴过来的设置
+          if (!this.property.isDataPreset) {
+            if (content) {
+              let oldData = {};
+              try {
+                oldData = JSON.parse(content) ?? {};
+              } catch (error) {
+                // 内容不是合法 JSON 时不能让组件停留在空数据上
+                console.error('组件内容解析失败,已使用默认内容', error);
               }
-              if (!p.style_mode) p.style_mode = 'big';
-              if (p.view_method === 'icon') {
-                p.file_name_display_mode = 'false';
-                p.view_method = 'independent';
-                p.style_mode = 'small';
+              if (oldData.type === 'audio') {
+                let p = oldData.property || {};
+                if (!p.file_name_display_mode) p.file_name_display_mode = 'true';
+                if (p.view_method === 'independent' && !p.style_mode) {
+                  p.style_mode = 'middle';
+                }
+                if (!p.style_mode) p.style_mode = 'big';
+                if (p.view_method === 'icon') {
+                  p.file_name_display_mode = 'false';
+                  p.view_method = 'independent';
+                  p.style_mode = 'small';
+                }
               }
-            }
-            this.data = mergeComponentData(this.data, oldData);
-          } else {
-            const bookUnifiedAttr = this.getBookUnifiedAttr();
+              this.data = mergeComponentData(this.data, oldData);
+            } else {
+              const bookUnifiedAttr = this.getBookUnifiedAttr();
 
-            this.$set(this.data, 'unified_attrib', bookUnifiedAttr);
+              this.$set(this.data, 'unified_attrib', bookUnifiedAttr);
 
-            // 初始化时,如果有 view_pinyin 则根据全教材设置配置设 view_pinyin 和 pinyin_position
-            if ('view_pinyin' in this.data.property) {
-              this.data.property.view_pinyin = bookUnifiedAttr?.view_pinyin ?? 'false';
-              this.data.property.pinyin_position = bookUnifiedAttr?.pinyin_position ?? 'top';
-            }
+              // 初始化时,如果有 view_pinyin 则根据全教材设置配置设 view_pinyin 和 pinyin_position
+              if ('view_pinyin' in this.data.property) {
+                this.data.property.view_pinyin = bookUnifiedAttr?.view_pinyin ?? 'false';
+                this.data.property.pinyin_position = bookUnifiedAttr?.pinyin_position ?? 'top';
+              }
 
-            if ('frame_color' in this.data.property) {
-              // 框颜色初始化为主题色
-              this.data.property.frame_color = bookUnifiedAttr?.topic_color ?? '#F13232';
-            }
+              if ('frame_color' in this.data.property) {
+                // 框颜色初始化为主题色
+                this.data.property.frame_color = bookUnifiedAttr?.topic_color ?? '#F13232';
+              }
 
-            if ('sn_background_color' in this.data.property) {
-              // 序号背景色
-              this.data.property.sn_background_color = bookUnifiedAttr?.topic_color ?? '#EA3232';
+              if ('sn_background_color' in this.data.property) {
+                // 序号背景色
+                this.data.property.sn_background_color = bookUnifiedAttr?.topic_color ?? '#EA3232';
+              }
             }
           }
 
@@ -223,17 +229,62 @@ const mixin = {
         });
     },
     /**
-     * @description 复制组件
+     * @description 复制组件(组件数据 + 组件背景)
      */
-    copyComponent() {
-      this.$emit('copyComponent', this.data);
+    async copyComponent() {
+      // 编辑器内容可能还未同步到 data,先同步再复制,避免复制到旧内容
+      this.syncRichTextContent();
+      const background = await this.getComponentBackground();
+      this.$emit('copyComponent', {
+        data: JSON.parse(JSON.stringify(this.data)),
+        background,
+      });
+    },
+    /**
+     * @description 获取组件背景(已加载过则直接复用,否则从服务端获取)
+     * @returns {Promise<String>} 组件背景 JSON 字符串
+     */
+    async getComponentBackground() {
+      const normalize = (background) =>
+        background ? (typeof background === 'string' ? background : JSON.stringify(background)) : '';
+
+      if (this.background) return normalize(this.background);
+      if (this.courseware_id === '' || this.id === '') return '';
+
+      // 与组件内容保持一致:从模板课件取内容时,背景也按模板组件的 id 取
+      const temporaryCoursewareID = this.getTemporaryCoursewareID();
+      const courseware_id = temporaryCoursewareID || this.courseware_id;
+      const component_id = temporaryCoursewareID.length > 0 ? this.oldId || this.id : this.id;
+
+      try {
+        const { background } = await GetCoursewareComponentBackground({ courseware_id, component_id });
+        return normalize(background);
+      } catch (error) {
+        console.error('组件背景获取失败', component_id, error);
+        return '';
+      }
     },
     /**
      * @description 设置组件数据(用于粘贴组件)
      * @param {Object} data 组件数据
+     * @param {String} background 组件背景 JSON 字符串
      */
-    setData(data) {
+    setData(data, background = '') {
+      // 标记内容已预设,避免初始化接口返回后再把粘贴过来的设置重置为默认值
+      this.property.isDataPreset = true;
+      this.property.isSilentPropertyWatch = true;
+      // 先卸载内容区,让依赖 isGetContent 渲染的编辑器(如富文本)用新内容重新初始化
+      this.property.isGetContent = false;
       this.data = data;
+      this.background = background;
+      this.$nextTick(() => {
+        this.property.isGetContent = true;
+        this.$nextTick(() => {
+          this.property.isSilentPropertyWatch = false;
+        });
+      });
+      // 背景由独立接口保存,粘贴后立即把源组件的背景写到新组件上
+      this.saveCoursewareComponentBackground();
     },
     /**
      * @description 显示设置
@@ -318,6 +369,21 @@ const mixin = {
         background: this.background,
       });
     },
+    /**
+     * @description 保存组件背景
+     * @param {String} background 组件背景 JSON 字符串
+     * @returns {Promise} 返回 Promise,便于父组件 await
+     */
+    saveCoursewareComponentBackground(background = this.background) {
+      if (!background || this.courseware_id === '' || this.id === '') return Promise.resolve();
+      return SaveCoursewareComponentBackground({
+        courseware_id: this.courseware_id,
+        component_id: this.id,
+        background: typeof background === 'string' ? background : JSON.stringify(background),
+      }).catch((error) => {
+        console.error('组件背景保存失败', this.id, error);
+      });
+    },
     syncRichTextContent() {
       const syncEditors = (children) => {
         children.forEach((child) => {