grapes.init.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. var faCogActive = true;
  2. var faThLargeActive = false;
  3. var activeIcon = getVariable('active_icon');
  4. if (activeIcon) {
  5. faCogActive = activeIcon === 'fa-cog'? true : false;
  6. faThLargeActive = activeIcon === 'fa-th-large'? true : false;
  7. }
  8. const panelsConfig = {
  9. stylePrefix: 'pn-', // 面板的样式前缀
  10. defaults: [
  11. {
  12. id: 'commands',
  13. buttons: [{}],
  14. },
  15. {
  16. id: 'options',
  17. buttons: [
  18. {
  19. active: false,
  20. id: 'sw-visibility',
  21. className: 'fa fa-square-o',
  22. command: 'core:component-outline',
  23. context: 'sw-visibility',
  24. attributes: { title: 'View components' },
  25. },
  26. {
  27. id: 'preview',
  28. className: 'fa fa-eye',
  29. command: 'preview',
  30. context: 'preview',
  31. attributes: { title: 'Preview' },
  32. },
  33. {
  34. id: 'fullscreen',
  35. className: 'fa fa-arrows-alt',
  36. command: 'fullscreen',
  37. context: 'fullscreen',
  38. attributes: { title: 'Fullscreen' },
  39. },
  40. // {
  41. // id: 'export-template',
  42. // className: 'fa fa-code',
  43. // command: 'export-template',
  44. // attributes: { title: 'View code' },
  45. // },
  46. ],
  47. },
  48. {
  49. id: 'views',
  50. buttons: [
  51. // {
  52. // id: 'open-sm',
  53. // className: 'fa fa-paint-brush',
  54. // command: 'open-sm',
  55. // active: false,
  56. // togglable: false,
  57. // attributes: { title: 'Open Style Manager' },
  58. // },
  59. {
  60. id: 'open-tm',
  61. className: 'fa fa-cog',
  62. command: 'open-tm',
  63. active: faCogActive,
  64. togglable: true,
  65. attributes: { title: 'Settings' },
  66. },
  67. // {
  68. // id: 'open-layers',
  69. // className: 'fa fa-bars',
  70. // command: 'open-layers',
  71. // togglable: false,
  72. // attributes: { title: 'Open Layer Manager' },
  73. // },
  74. {
  75. id: 'open-blocks',
  76. className: 'fa fa-th-large',
  77. command: 'open-blocks',
  78. active: faThLargeActive,
  79. togglable: true,
  80. attributes: { title: 'Open Blocks' },
  81. },
  82. ],
  83. },
  84. ],
  85. };
  86. // 定义自定义组件类型
  87. const myNewComponentTypes = (editor) => {
  88. //连接属性
  89. // editor.Components.addType('a', {
  90. // isComponent: (el) => el.tagName === 'A',
  91. // model: {
  92. // defaults: {
  93. // traits: [
  94. // {
  95. // type: 'text', // Type of the trait
  96. // name: 'href', // (required) The name of the attribute/property to use on component
  97. // label: 'URL', // The label you will see in Settings
  98. // }
  99. // ],
  100. // },
  101. // },
  102. // });
  103. //图片属性
  104. editor.Components.addType('img', {
  105. isComponent: (el) => el.tagName === 'IMG',
  106. model: {
  107. defaults: {
  108. traits: [
  109. {
  110. type: 'text', // Type of the trait
  111. name: 'title', // (required) The name of the attribute/property to use on component
  112. label: 'title', // The label you will see in Settings
  113. },
  114. {
  115. type: 'text', // Type of the trait
  116. name: 'width', // (required) The name of the attribute/property to use on component
  117. label: 'width', // The label you will see in Settings
  118. },
  119. {
  120. type: 'text', // Type of the trait
  121. name: 'height', // (required) The name of the attribute/property to use on component
  122. label: 'height', // The label you will see in Settings
  123. },
  124. ],
  125. },
  126. },
  127. });
  128. };
  129. const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
  130. // 创建 GrapesJS 编辑器实例
  131. const editor = grapesjs.init({
  132. container: '#mtb_visual_editor', // 指定编辑器容器的 DOM 元素
  133. fromElement: true, // 从 DOM 元素中加载初始内容
  134. height: '100%', // 设置编辑器的高度
  135. width: '100%', // 设置宽度自适应
  136. storageManager: false,
  137. panels: panelsConfig,
  138. plugins: [myNewComponentTypes],
  139. assetManager: {
  140. upload: '/dist/visual-editor/upload',
  141. uploadName: '_file_',
  142. multiUpload:false,
  143. headers: {
  144. 'X-CSRF-TOKEN': csrfToken,
  145. },
  146. },
  147. });
  148. //定义block块
  149. const bm = editor.Blocks; // `Blocks` is an alias of `BlockManager`
  150. bm.add('block_p', {
  151. // Your block properties...
  152. label: 'Paragraph',
  153. media: `<svg style="width:20px;height:20px" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2024 Fonticons, Inc.--><path d="M192 32l64 0 160 0c17.7 0 32 14.3 32 32s-14.3 32-32 32l-32 0 0 352c0 17.7-14.3 32-32 32s-32-14.3-32-32l0-352-32 0 0 352c0 17.7-14.3 32-32 32s-32-14.3-32-32l0-96-32 0c-88.4 0-160-71.6-160-160s71.6-160 160-160z"/></svg>`,
  154. content: '<p>insert your text here</p>',
  155. });
  156. bm.add('block_span', {
  157. // Your block properties...
  158. label: 'Text',
  159. media: `<svg style="width:20px;height:20px" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2024 Fonticons, Inc.--><path d="M32 32C14.3 32 0 46.3 0 64S14.3 96 32 96l128 0 0 352c0 17.7 14.3 32 32 32s32-14.3 32-32l0-352 128 0c17.7 0 32-14.3 32-32s-14.3-32-32-32L192 32 32 32z"/></svg>`,
  160. content: '<span>insert your text here</span>',
  161. });
  162. //图片管理器
  163. const am = editor.AssetManager;
  164. // 锁定整个画布
  165. editor.getWrapper().set({ locked: true });
  166. // 遍历所有组件并解锁具有edit属性的组件
  167. // const edit_classes = ['mtb_edit']; // 定义需要解锁的组件类名
  168. editor.getComponents().each(component => {
  169. component.onAll(component => {
  170. //解销CLASS
  171. // let html = component.toHTML();
  172. // const classes = component.getClasses();
  173. // // 判断是否有交集
  174. // const hasIntersection = classes.some(item => {
  175. // // 如果是数组,则递归检查子数组
  176. // if (Array.isArray(item)) {
  177. // return item.some(subItem => edit_classes.includes(subItem));
  178. // }
  179. // // 如果是字符串,直接检查是否在 edit_classes 中
  180. // return edit_classes.includes(item);
  181. // });
  182. // 如果有交集,解锁组件
  183. if (component.get('attributes').mtb_edit == 'true') {
  184. component.set({ locked: false });
  185. setBorder(component);
  186. }
  187. if (component.get('attributes').mtb_edit == 'false') {
  188. component.set({ locked: true });
  189. }
  190. if (component.get('attributes').mtb_edit_this == 'true') {
  191. component.set({ locked: false });
  192. setBorder(component);
  193. //关闭子组件
  194. component.forEachChild(child => {
  195. child.set({ locked: true });
  196. })
  197. }
  198. if (component.get('attributes').mtb_edit_this == 'false') {
  199. component.set({ locked: true });
  200. }
  201. })
  202. });
  203. function setBorder(component) {
  204. if (component.attributes.tagName == 'a') {
  205. component.setStyle({
  206. border: '2px dotted #f08300'
  207. });
  208. } else {
  209. component.setStyle({
  210. border: '1px dotted #3b97e3'
  211. });
  212. }
  213. }
  214. // 监听组件选择事件
  215. editor.on('component:selected', (comp) => {
  216. //去掉选中组件后的按钮
  217. const selectedComponent = editor.getSelected();
  218. //const defaultToolbar = selectedComponent.get('toolbar');
  219. //最外层不显示按钮
  220. if (selectedComponent.get('attributes').mtb_edit == 'true' || selectedComponent.get('attributes').mtb_edit_this == 'true') {
  221. selectedComponent.set({
  222. toolbar: [
  223. ]
  224. });
  225. } else {
  226. selectedComponent.set({
  227. // toolbar: [ ...defaultToolbar, { attributes: {class: commandIcon}, command: commandToAdd}]
  228. toolbar: [{
  229. attributes: { class: 'fa fa-clone' },
  230. command: 'tlb-clone',
  231. title: 'Clone',
  232. }, {
  233. attributes: { class: 'fa fa-trash' },
  234. command: 'tlb-delete',
  235. title: 'Delete',
  236. }]
  237. });
  238. }
  239. // 双击图片时弹出图片管理器
  240. if (selectedComponent.attributes.tagName == 'img') {
  241. //双击图片时弹出图片管理器
  242. const el = selectedComponent.getEl();
  243. // 添加双击事件监听器
  244. el.addEventListener('dblclick', () => {
  245. am.open({
  246. types: ['image'], // This is the default option
  247. select(asset, complete) {
  248. const selected = editor.getSelected();
  249. if (selected) {
  250. selected.addAttributes({ src: asset.getSrc() });
  251. complete && am.close();
  252. }
  253. },
  254. });
  255. });
  256. }
  257. //其他
  258. });
  259. // 隐藏或显示左侧面板
  260. function leftPanelDisplay(isShow = true) {
  261. if (isShow) {
  262. let elements1 = document.querySelectorAll('.gjs-pn-views-container');
  263. elements1.forEach(function(element) {
  264. element.style.display = 'block'; // 或者 'flex',取决于你希望如何显示这些元素
  265. });
  266. let elements2 = document.querySelectorAll('.gjs-pn-views');
  267. elements2.forEach(function(element) {
  268. element.style = 'border_bottom: 2px solid var(--gjs-main-dark-color)';
  269. });
  270. } else {
  271. let elements1 = document.querySelectorAll('.gjs-pn-views-container');
  272. elements1.forEach(function(element) {
  273. element.style.display = 'none'; // 或者 'flex',取决于你希望如何显示这些元素
  274. });
  275. let elements2 = document.querySelectorAll('.gjs-pn-views');
  276. elements2.forEach(function(element) {
  277. element.style = 'border-bottom:none';
  278. });
  279. }
  280. }
  281. // 监听编辑器加载完成事件
  282. editor.on('load', () => {
  283. //----------
  284. // 下接菜单
  285. //----------
  286. // 获取目标元素
  287. const targetElement = document.querySelector('.fa-arrows-alt');
  288. // 创建下拉选择框
  289. const dropdown = document.createElement('select');
  290. dropdown.className = 'custom-select'; // 添加自定义样式类
  291. dropdown.id = 'dropdown'; // 添加 id 属性
  292. // 构建 option 标签
  293. var options = '';
  294. siteMenu.forEach(function (item) {
  295. if (mid == item.id) {
  296. options += `<option value="${item.id}" uri="${item.url}" selected>${item.title}</option>`;
  297. } else {
  298. options += `<option value="${item.id}" uri="${item.url}">${item.title}</option>`;
  299. }
  300. });
  301. // 将生成的 option 标签添加到 dropdown 中
  302. dropdown.innerHTML = options;
  303. // 将下拉选择框插入到目标元素之后
  304. targetElement.insertAdjacentElement('afterend', dropdown);
  305. dropdownel = document.getElementById('dropdown');
  306. // 监听 change 事件
  307. dropdownel.addEventListener('change', function () {
  308. // 获取选中的 option
  309. var selectedOption = dropdownel.options[dropdownel.selectedIndex];
  310. // 获取选中的 id 和 uri
  311. var id = selectedOption.value;
  312. var uri = selectedOption.getAttribute('uri');
  313. if (id > 0) {
  314. // 生成跳转的 URL
  315. var redirectUrl = `?mid=${id}&uri=${encodeURIComponent(uri)}`;
  316. // 跳转到生成的 URL
  317. window.location.href = redirectUrl;
  318. }
  319. });
  320. //----------
  321. //发布
  322. //----------
  323. customSelect = document.querySelector('.custom-select');
  324. // 创建 sendButton 按钮
  325. const sendButton = document.createElement('button');
  326. sendButton.textContent = publishBtnName; // 按钮文本
  327. sendButton.classList.add('send-button');
  328. sendButton.classList.add('layui-btn');
  329. sendButton.classList.add('layui-btn-radius');
  330. sendButton.classList.add('layui-btn-radius');
  331. sendButton.style = 'margin-left:10px;height:25px;line-height:25px;padding:0 10px;vertical-align:unset;'; // 添加样式(可选)
  332. customSelect.insertAdjacentElement('afterend', sendButton);
  333. //发布按钮点击事件
  334. sendButton.addEventListener('click', function () {
  335. // 显示loading
  336. loadIndex = layer.load(0, {shade: [0.5, '#000']});
  337. // 发送数据
  338. $.ajax({
  339. url: '/dist/visual-editor/publish',
  340. type: 'POST',
  341. headers: {
  342. 'X-CSRF-TOKEN': csrfToken,
  343. },
  344. data: {},
  345. success: function (res) {
  346. layer.close(loadIndex);
  347. layer.msg(res.message,{shade: [0.5, '#000']});
  348. },
  349. error: function (err) {
  350. layer.close(loadIndex);
  351. layer.msg(err,{shade: [0.5, '#000']});
  352. }
  353. });
  354. });
  355. //----------
  356. // 右侧面板显示隐藏
  357. //----------
  358. // 监听属性按钮点击事件
  359. var gjsPnBtn = document.querySelectorAll('.gjs-pn-btn');
  360. var headRightBtn = ['fa-cog', 'fa-th-large'];
  361. gjsPnBtn.forEach(function(icon1) {
  362. let hasIntersection = headRightBtn.some(function(btnClass) {
  363. return icon1.classList.contains(btnClass);
  364. });
  365. if (hasIntersection) {
  366. icon1.addEventListener('click', function() {
  367. hasActive = false;
  368. gjsPnBtn.forEach(function(icon) {
  369. if (icon.classList.contains('gjs-pn-active')) {
  370. hasActive = true;
  371. saveVariable('active_icon',icon.classList.item(2));
  372. }
  373. });
  374. if (hasActive) {
  375. leftPanelDisplay(true);
  376. } else {
  377. leftPanelDisplay(false);
  378. saveVariable('active_icon','none');
  379. }
  380. });
  381. }
  382. });
  383. //右侧面板显示隐藏
  384. if (faCogActive === false && faThLargeActive === false) {
  385. leftPanelDisplay(false)
  386. }
  387. //----------
  388. //关闭loading
  389. //----------
  390. layer.close(loadIndex);
  391. });
  392. //保存模版内容
  393. editor.on('update', () => {
  394. const html = editor.getHtml();
  395. // 你可以在这里添加自定义逻辑
  396. //ajax提交数据
  397. $.ajax({
  398. url: '/dist/visual-editor/preview-save',
  399. type: 'POST',
  400. headers: {
  401. 'X-CSRF-TOKEN': csrfToken,
  402. },
  403. data: { // 发送数据
  404. html: html
  405. },
  406. success: function (res) {
  407. if (res.status != 1) {
  408. layer.msg('save data error, please try again later!',{shade: [0.5, '#000']});
  409. }
  410. },
  411. error: function (err) {
  412. alert(err);
  413. }
  414. });
  415. });
  416. // 上传图片时触发loading效果
  417. editor.on('asset:upload:start', () => {
  418. loadIndex = layer.load(0, {shade: [0.5, '#000']});
  419. });
  420. editor.on('asset:upload:end', () => {
  421. layer.close(loadIndex);
  422. });
  423. // 图片懒加载
  424. layui.use('flow', function(){
  425. var flow = layui.flow;
  426. //当你执行这样一个方法时,即对页面中的全部带有 lay-src 的 img 元素开启了懒加载(当然你也可以指定相关 img)
  427. flow.lazyimg();
  428. });
  429. // 保存变量到LocalStorage
  430. function saveVariable(name, value) {
  431. localStorage.setItem(name, JSON.stringify(value));
  432. }
  433. // 从LocalStorage读取变量
  434. function getVariable(name) {
  435. const value = localStorage.getItem(name);
  436. return value ? JSON.parse(value) : null;
  437. }