vue.rules.js 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318
  1. /**
  2. * The Vue application instance.
  3. * https://vuejs.org/guide/essentials/application.html
  4. * This is the root component
  5. */
  6. const app = Vue.createApp({
  7. /**
  8. * to prevent conflict with jekyll we change the
  9. * delimiters from {{ }} to [[ ]]
  10. */
  11. delimiters: ['[[', ']]'],
  12. /**
  13. * The data object of the root component.
  14. * These variables are available in the html template.
  15. */
  16. data() {
  17. return {
  18. // The rule object
  19. rule: global.rule || {
  20. ruleID: "",
  21. timestamp: "",
  22. icon: "",
  23. name: "",
  24. lineage: "",
  25. summary: "",
  26. config: {},
  27. creator: {
  28. name: "",
  29. url: "",
  30. },
  31. modules: [],
  32. latest_version: 1,
  33. list: "",
  34. deleted: 0,
  35. forked: 0,
  36. edit_history: []
  37. },
  38. legacy: false,
  39. rID: false,
  40. loading: false,
  41. publishing: false,
  42. edit: false,
  43. isOwner: false,
  44. isAdmin: false,
  45. view: (global.rule) ? true : false,
  46. preview: (global.rule) ? true : false,
  47. template: (global.rule) ? true : false,
  48. steinAPI: 'https://api.steinhq.com/v1/storages/5e8b937ab88d3d04ae0816a5',
  49. backendUrl: 'http://localhost:3000/api/publish_rule',
  50. backendUrlrule: 'http://localhost:3000/api/get_rule',
  51. backedDeleterule: 'http://localhost:3000/api/delete_rule',
  52. adminMail: "communityrule@medlab.host",
  53. // TODO keep an array of past states for undo/redo
  54. history: [],
  55. // the data of the current module in the editor
  56. editor: {
  57. source: null,
  58. previousState: null,
  59. module: null,
  60. },
  61. // the module that is currently being dragged
  62. holding: false,
  63. // object of icons for easy access
  64. icons: {
  65. plus: '/assets/tabler_icons/circle-plus.svg',
  66. info: '/assets/tabler_icons/info-circle.svg',
  67. chevron: '/assets/tabler_icons/chevrons-down.svg',
  68. blank: '/assets/tabler_icons/circle-dotted.svg',
  69. view: '/assets/tabler_icons/eye.svg',
  70. edit: '/assets/tabler_icons/tool.svg',
  71. plus: '/assets/tabler_icons/plus.svg',
  72. minus: '/assets/tabler_icons/minus.svg',
  73. publish: '/assets/tabler_icons/cloud-upload.svg',
  74. download: '/assets/tabler_icons/download.svg',
  75. export: '/assets/tabler_icons/file-download.svg',
  76. upload: '/assets/tabler_icons/file-upload.svg',
  77. fork: '/assets/tabler_icons/git-fork.svg',
  78. delete: '/assets/tabler_icons/x.svg',
  79. edit: '/assets/tabler_icons/edit.svg',
  80. arrow: '/assets/tabler_icons/arrow-narrow-left.svg'
  81. },
  82. // icons available in the editor
  83. moduleIcons: {
  84. culture: '/assets/tabler_icons/palette.svg',
  85. decision: '/assets/tabler_icons/thumb-up.svg',
  86. process: '/assets/tabler_icons/rotate.svg',
  87. structure: '/assets/tabler_icons/building.svg',
  88. relationship: '/assets/tabler_icons/heart.svg',
  89. economic: '/assets/tabler_icons/coin.svg',
  90. legal: '/assets/tabler_icons/license.svg',
  91. map: '/assets/tabler_icons/map.svg',
  92. communications: '/assets/tabler_icons/microphone.svg',
  93. },
  94. // icons available for rules
  95. ruleIcons: {
  96. atom: '/assets/tabler_icons/atom.svg',
  97. bandage: '/assets/tabler_icons/bandage.svg',
  98. book: '/assets/tabler_icons/book.svg',
  99. box: '/assets/tabler_icons/box.svg',
  100. church: '/assets/tabler_icons/building-church.svg',
  101. store: '/assets/tabler_icons/building-store.svg',
  102. brush: '/assets/tabler_icons/brush.svg',
  103. car: '/assets/tabler_icons/car.svg',
  104. clock: '/assets/tabler_icons/clock.svg',
  105. cloud: '/assets/tabler_icons/cloud.svg',
  106. compass: '/assets/tabler_icons/compass.svg',
  107. game: '/assets/tabler_icons/device-gamepad.svg',
  108. flask: '/assets/tabler_icons/flask.svg',
  109. location: '/assets/tabler_icons/location.svg',
  110. moon: '/assets/tabler_icons/moon.svg',
  111. settings: '/assets/tabler_icons/settings.svg',
  112. shield: '/assets/tabler_icons/shield.svg',
  113. star: '/assets/tabler_icons/star.svg',
  114. tool: '/assets/tabler_icons/tool.svg',
  115. world: '/assets/tabler_icons/world.svg',
  116. },
  117. // the template for modules
  118. moduleTemplate: {
  119. moduleID: "",
  120. name: "",
  121. icon: "",
  122. summary: "",
  123. config: {},
  124. type: "",
  125. modules: []
  126. },
  127. // tracks the current module library tab that is open
  128. moduleLibrary: 'culture',
  129. moduleTypes: {
  130. // custom: {
  131. // question: 'Modules that you\'ve created.',
  132. // icon: '/assets/tabler_icons/circle-plus.svg',
  133. // open: true
  134. // },
  135. culture: {
  136. question: 'What are the core missions, values, and norms?',
  137. icon: '/assets/tabler_icons/palette.svg',
  138. open: true
  139. },
  140. decision: {
  141. question: 'Who can make decisions and how?',
  142. icon: '/assets/tabler_icons/thumb-up.svg',
  143. open: false
  144. },
  145. process: {
  146. question: 'How are policies implemented, and how do they evolve?',
  147. icon: '/assets/tabler_icons/rotate.svg ',
  148. open: false
  149. },
  150. structure: {
  151. question: 'What kinds of roles and internal entities are there?',
  152. icon: '/assets/tabler_icons/building.svg',
  153. open: false
  154. }
  155. },
  156. // array of modules that have been created by the user
  157. // TODO: implement custom modules
  158. customModules: [],
  159. // library of existing modules
  160. modules: global.modules,
  161. exports: {
  162. markdown: null,
  163. json: null,
  164. }
  165. }
  166. },
  167. /**
  168. * Vue provide passes data to other components.
  169. * https://vuejs.org/guide/components/provide-inject.html#provide-inject
  170. */
  171. provide() {
  172. return {
  173. editor: this.editor,
  174. icons: this.icons,
  175. }
  176. },
  177. created() {
  178. this.addToEditor(this.newModule());
  179. var urlParams = new URLSearchParams(window.location.search);
  180. if (urlParams.has('r')) {
  181. this.rID = urlParams.get('r');
  182. this.preview = true;
  183. this.view = true;
  184. this.fetchRule(this.rID);
  185. }
  186. },
  187. computed: {
  188. /**
  189. * Exports the current rule into a normalized format
  190. * Cleans up all submodules so they are ready for export
  191. * @returns {Object} a Rule object
  192. */
  193. ruleExport() {
  194. //TODO: test if icon is an absolute url and only add the global if it is not
  195. /**
  196. * Takes a module and recursively cleans it and all submodules up
  197. * @param {Object} module a module object
  198. * @returns
  199. */
  200. function cleanModules(module) {
  201. const newModule = {
  202. moduleID: module.moduleID,
  203. name: module.name,
  204. icon: (module.icon && !module.icon.includes('http')) ? global.url + module.icon : module.icon,
  205. summary: module.summary,
  206. config: module.config,
  207. type: module.type,
  208. modules: (module.modules) ? module.modules.map(cleanModules) : [],
  209. }
  210. return newModule;
  211. }
  212. return {
  213. ruleID: (this.rule.ruleID) ? this.rule.ruleID : this.slugify(this.rule.name),
  214. timestamp: this.timesString(),
  215. icon: (this.rule.icon && !this.rule.icon.includes('http')) ? global.url + this.rule.icon : this.rule.icon,
  216. name: this.rule.name,
  217. lineage: this.rule.lineage,
  218. summary: this.rule.summary,
  219. config: this.rule.config,
  220. creator: {
  221. name: this.rule.creator.name,
  222. url: this.rule.creator.url,
  223. },
  224. modules: this.rule.modules.map(cleanModules)
  225. }
  226. },
  227. /**
  228. * @returns {String} the current rule as a JSON string
  229. */
  230. json() {
  231. return JSON.stringify(this.ruleExport, null, 2);
  232. },
  233. /**
  234. * Creates an array of all moduleIDs in use
  235. * @returns {Array} an array of all module's (in the library and custom modules) moduleID
  236. */
  237. listModuleIds() {
  238. const modules = [...this.rule.modules, ...this.customModules];
  239. return modules.map(module => module.moduleID)
  240. },
  241. /**
  242. * @returns {Object} the current module in the editor
  243. */
  244. moduleInEditor() {
  245. return this.moduleEditor[0]
  246. },
  247. /**
  248. * Tests if the current module in the editor has been modified
  249. * against the editor.previousState object
  250. * @returns {Boolean} true if the module in the editor has been modified
  251. */
  252. //TODO: find a more accurate solution than just turning the object into a string
  253. editorHasEdits() {
  254. return this.editor.module && Object.entries(this.editor.module).toString() !== Object.entries(this.editor.previousState).toString();
  255. },
  256. },
  257. methods: {
  258. // module methods ===========================================================
  259. /**
  260. * @returns {Object} a new module object from the moduleTemplate
  261. */
  262. newModule() {
  263. return JSON.parse(JSON.stringify(this.moduleTemplate));
  264. },
  265. /**
  266. * spreads a source module into a new module from the moduleTemplate
  267. * @param {Object} sourceModule the module to copy
  268. * @param {Boolean} includeSubmodules whether to copy submodules or not
  269. * @returns
  270. */
  271. cloneModule(sourceModule, includeSubmodules) {
  272. let output = {
  273. ...this.moduleTemplate,
  274. ...sourceModule,
  275. //TODO: implement lineage pattern, same as the rule does
  276. source: sourceModule, // keep track of where this module came from
  277. };
  278. if (!includeSubmodules) output.modules = [];
  279. // clear configs
  280. document.getElementById("newConfigKey").value =
  281. "Configuration";
  282. document.getElementById("newConfigValue").value =
  283. "Value";
  284. // delete unnecessary properties
  285. delete output.content;
  286. delete output.readonly;
  287. // TODO: give module a unique id
  288. // if (output.moduleID) output.moduleID = this.getUniqueId(output.moduleID);
  289. return output;
  290. },
  291. /**
  292. * Handles the click event to copy a module
  293. * @param {Event} ev the click event
  294. */
  295. handleClickCopyModule(ev) {
  296. const clickTarget = this.getClosestModule(ev.target);
  297. if (!clickTarget) return;
  298. this.copyModule(clickTarget.module);
  299. },
  300. /**
  301. * Handles the click event to edit a module
  302. * @param {Event} ev the click event
  303. */
  304. handleClickEditModule(ev) {
  305. const clickTarget = this.getClosestModule(ev.target);
  306. if (!clickTarget) return;
  307. this.editModule(clickTarget.module);
  308. },
  309. /**
  310. * Copies a module to the editor
  311. * @param {Object} module the module to copy
  312. */
  313. copyModule(module) {
  314. this.copyToEditor(module);
  315. },
  316. /**
  317. * moves a module to the editor
  318. * @param {Object} module the module to edit
  319. */
  320. editModule(module) {
  321. this.addToEditor(module);
  322. },
  323. /**
  324. * add a module to another module (or to the rule by default) as a submodule
  325. * @param {Object} module to add
  326. * @param {Object} target a module or the rule Object where the module should be added as a submodule
  327. */
  328. addModule(module, target = this.rule) {
  329. target.modules.push(module);
  330. },
  331. /**
  332. * remove a module from another module (or from the rule)
  333. * recursively moves through all submodules in the target
  334. * removes ONLY the first instance of the module
  335. * @param {Object} module the module to remove from target
  336. * @param {Object} target the module or rule to remove the module from (defaults to rule)
  337. */
  338. removeModule(module, target = this.rule) {
  339. if (!this.moduleContains(module, target)) return; // if the module is not in the target, do nothing
  340. //
  341. target.modules.forEach((m, idx) => {
  342. if (m === module) {
  343. target.modules.splice(idx, 1);
  344. return;
  345. } else {
  346. this.removeModule(module, m);
  347. }
  348. });
  349. },
  350. /**
  351. * Deletes custom module from the customModules array and clears the editor
  352. * @param {Object} module the module to be deleted
  353. */
  354. deleteModule(module) {
  355. this.removeCustomModule(module);
  356. // TODO: only clear the editor if the module is present in the editor
  357. this.clearEditor();
  358. },
  359. /**
  360. * Handles the start drag event for a module
  361. * @param {Event} ev the drag event
  362. */
  363. startDragModule(ev) {
  364. const targetModule = this.getClosestModule(ev.target);
  365. if (!targetModule) return;
  366. const module = targetModule.module;
  367. ev.dataTransfer.setDragImage(targetModule, ev.offsetX, ev.offsetY);
  368. this.holding = { module };
  369. },
  370. /**
  371. * Handles the start drag event for a module
  372. * when the module is being rearranged within the rule
  373. * @param {Event} ev the drag event
  374. */
  375. rearrangeModule(ev) {
  376. const targetModule = this.getClosestModule(ev.target);
  377. if (!targetModule) return;
  378. const source = this.getClosestModule(targetModule.parentNode).module;
  379. const module = targetModule.module;
  380. ev.dataTransfer.setDragImage(targetModule, ev.offsetX, ev.offsetY);
  381. this.holding = {
  382. module,
  383. source,
  384. };
  385. },
  386. /**
  387. * Handles the dragend event for a module
  388. */
  389. endDragModule() {
  390. this.holding = false;
  391. },
  392. /**
  393. * Recursively searches modules and their submodules for a module
  394. * @param {Object} needle the module to search for
  395. * @param {Object} haystack the module to search in (defaults to rule)
  396. * @returns {Boolean} true if the module is in the haystack
  397. */
  398. // TODO: return the module location in the haystack (Maybe?)
  399. moduleContains(needle, haystack = this.rule) {
  400. if (!haystack.modules) return false; // does the haystack even have modules?
  401. if (haystack.modules.includes(needle)) return true; // is the needle in the haystack?
  402. return haystack.modules.some(submodule => this.moduleContains(needle, submodule)); // is the needle in any of the submodules?
  403. },
  404. // rule methods ===========================================================
  405. /**
  406. * Handles the drop event for a module
  407. * adds the module to the closest submodule or the rule depending on what it is dropped onto
  408. * then adds the module to the editor
  409. * @param {Event} ev the drop event
  410. */
  411. dropOnRule(ev) {
  412. //TODO browser drag objects that hover over drop zone are showing a 'add' icon
  413. const landingNode = this.getClosestModule(ev.target);
  414. if (!this.holding.module || !landingNode) return; // if there is no module to drop or no landing node, do nothing
  415. const landingModule = landingNode.module; // module is set with the v-bind prop binding
  416. const holdingModule = this.holding.module;
  417. if (holdingModule === landingModule) return; // if the module is the same, do nothing
  418. // if the module being dropped is readyonly clone it, otherwise use the original
  419. const readonly = holdingModule.readonly;
  420. const module = (readonly) ? this.cloneModule(holdingModule) : holdingModule;
  421. if (this.holding.source) {
  422. // if the module has a source, remove it from that source
  423. this.removeModule(holdingModule, this.holding.source);
  424. }
  425. this.addModule(module, landingModule);
  426. this.editModule(module);
  427. this.endDragModule();
  428. },
  429. fetchRule(id) {
  430. this.loading = true;
  431. // handle legacy links
  432. // TODO: handle this at a global level
  433. let redirect = {
  434. 'benevolent_dictator': 'benevolent-dictator',
  435. circles: 'circles',
  436. consensus: 'consensus',
  437. 'do-ocracy': 'do-ocracy',
  438. 'elected_board': 'elected-board',
  439. jury: 'jury',
  440. petition: 'petition',
  441. 'self-appointed_board': 'self-appointed-board',
  442. }
  443. // if the rule is a legacy link, redirect
  444. if (redirect[id]) {
  445. location.href = `/templates/${redirect[id]}`;
  446. return;
  447. }
  448. const store = new SteinStore(
  449. this.steinAPI
  450. );
  451. const backendUrlGetRule = this.backendUrlrule + "?ruleId=" + id;
  452. (async () => {
  453. var rule = [];
  454. // read values from all sheets
  455. await fetch(backendUrlGetRule, {
  456. method: 'GET',
  457. headers: {
  458. 'Content-Type': 'application/json',
  459. // Add any other headers you may need, such as authorization headers
  460. },
  461. }).then(response => {
  462. if (!response.ok) {
  463. throw new Error('Network response was not ok');
  464. }
  465. return response.json(); // This returns another Promise
  466. })
  467. .then(data => {
  468. if (data.rules.length > 0) {
  469. rule = JSON.parse(data.rules)[0];
  470. }
  471. });
  472. // no rule found, exit
  473. // TODO: inform the user that the rule was not found
  474. if (!rule) {
  475. this.loading = false;
  476. return;
  477. }
  478. // if this is a legacy (pre-v3) set it as such
  479. if (rule.version < 3) {
  480. this.loading = false;
  481. this.legacy = true;
  482. this.rule = rule;
  483. Vue.nextTick(() => {
  484. if (rule.version == 2) displayBuilderHTML();
  485. });
  486. return;
  487. }
  488. const splitArray = rule.list.split(':');
  489. const resultArray = splitArray.filter(value => value.trim() !== '');
  490. var forkedOrNot = 0
  491. if (resultArray.length == 1) {
  492. forkedOrNot = 1;
  493. }
  494. this.rule = {
  495. ruleID: rule.rule_id,
  496. timestamp: rule.time_stamp,
  497. icon: rule.icon,
  498. name: rule.name,
  499. lineage: rule.lineage,
  500. summary: rule.summary,
  501. config: rule.config,
  502. creator: {
  503. name: rule.creator_name,
  504. url: rule.creator_url,
  505. },
  506. modules: (rule.modules) ? JSON.parse(rule.modules) : [],
  507. latest_version: rule.latest_version,
  508. list: rule.list,
  509. forked: forkedOrNot,
  510. deleted: rule.deleted,
  511. edit_history: resultArray
  512. }
  513. if (rule.email == localStorage.getItem('userEmail')) {
  514. this.isOwner = true;
  515. this.isAdmin = true; // this will allow the user to delete his own rules
  516. }
  517. if (localStorage.getItem('userEmail') == this.adminMail) {
  518. this.isAdmin = true;
  519. }
  520. /** Add name to <title> for v3+ rules */
  521. document.title = rule.name + " / CommunityRule"
  522. this.loading = false;
  523. })();
  524. /*fetch(backendUrlGetRule, {
  525. method: 'GET',
  526. headers: {
  527. 'Content-Type': 'application/json',
  528. // Add any other headers you may need, such as authorization headers
  529. },
  530. }).then(response => {
  531. if (!response.ok) {
  532. throw new Error('Network response was not ok');
  533. }
  534. return response.json(); // This returns another Promise
  535. }).then (data => {
  536. var rule = [];
  537. if (data.rules.length > 0) {
  538. rule = data.rules;
  539. }
  540. // no rule found, exit
  541. // TODO: inform the user that the rule was not found
  542. if (!rule) {
  543. this.loading = false;
  544. return;
  545. }
  546. // if this is a legacy (pre-v3) set it as such
  547. if (rule.version < 3) {
  548. this.loading = false;
  549. this.legacy = true;
  550. this.rule = rule;
  551. Vue.nextTick(() => {
  552. if (rule.version == 2) displayBuilderHTML();
  553. });
  554. return;
  555. }
  556. this.rule = {
  557. ruleID: rule.ruleID,
  558. timestamp: rule.timestamp,
  559. icon: rule.icon,
  560. name: rule.name,
  561. lineage: rule.lineage,
  562. summary: rule.summary,
  563. config: rule.config,
  564. creator: {
  565. name: rule.creatorName,
  566. url: rule.creatorUrl,
  567. },
  568. modules: (rule.modules) ? JSON.parse(rule.modules) : []
  569. }
  570. document.title = rule.name + " / CommunityRule"
  571. this.loading = false;
  572. }); */
  573. },
  574. getRuleLink(ruleId) {
  575. // Further split each part based on '@'
  576. const subParts = ruleId.split('@');
  577. // Use the desired sub-part in your link construction
  578. // For example, if you want the first sub-part after splitting on '@'
  579. const finalPart = subParts[0];
  580. return `/create/?r=${finalPart}`;
  581. },
  582. getRuleName(ruleId) {
  583. // Further split each part based on '@'
  584. const subParts = ruleId.split('@');
  585. // Use the desired sub-part in your link construction
  586. // For example, if you want the first sub-part after splitting on '@'
  587. const ruleName = subParts[1];
  588. return ruleName
  589. },
  590. // editor methods =========================================================
  591. clickDelete() {
  592. (async () => {
  593. // read values from all sheets
  594. const requestData = {
  595. ruleID: this.rule.ruleID
  596. }
  597. await fetch(this.backedDeleterule, {
  598. method: 'DELETE',
  599. headers: {
  600. 'Content-Type': 'application/json',
  601. // Add any other headers you may need, such as authorization headers
  602. },
  603. body: JSON.stringify(requestData),
  604. }).then(response => {
  605. if (!response.ok) {
  606. throw new Error('Network response was not ok');
  607. }
  608. alert("Error while deleting rule");
  609. return response.json(); // This returns another Promise
  610. }).then(data => {
  611. alert('Rule deleted successfully');
  612. window.open("/library", false);
  613. });
  614. this.loading = false;
  615. })();
  616. },
  617. /**
  618. * Adds a module to the editor
  619. * @param {Object} module the module to add to the editor
  620. */
  621. addToEditor(module) {
  622. this.preventEditorLoss();
  623. this.setEditorSource(module);
  624. this.setEditorPreviousState(module);
  625. this.editor.module = module;
  626. },
  627. /**
  628. * Copies a module to the editor
  629. * @param {Object} module the module to copy to the editor
  630. */
  631. copyToEditor(module) {
  632. const moduleCopy = this.cloneModule(module);
  633. this.preventEditorLoss();
  634. this.setEditorSource(module);
  635. this.setEditorPreviousState(moduleCopy);
  636. this.editor.module = moduleCopy;
  637. },
  638. /**
  639. * Takes a module and clones it into the editor.previousState
  640. * @param {Object} module the module to add to the previous state
  641. */
  642. setEditorPreviousState(module) {
  643. this.editor.previousState = { ...module };
  644. },
  645. /**
  646. * Sets the editor.source to the module
  647. * @param {Object} module the module to set the editor source to
  648. */
  649. setEditorSource(module) {
  650. this.editor.source = module;
  651. },
  652. /**
  653. * Checks if the editor has edits and that the current module in the editor is not present in the rule
  654. * If the module in the editor would be lost, confirm with the user
  655. * then adds the module to the customModules array
  656. */
  657. preventEditorLoss() {
  658. // if the editor has changes and the module isn't in the rule, save it to the custom modules
  659. if (this.editorHasEdits && !this.moduleContains(this.editor.module)) {
  660. this.confirm('You have unsaved changes. Are you sure you want to discard them?')
  661. this.addCustomModule(this.editor.module);
  662. }
  663. },
  664. /**
  665. * Handles the click event for adding a module from the editor to the rule
  666. */
  667. clickAddModule() {
  668. const module = this.editor.module;
  669. this.addModule(module);
  670. this.addToEditor(module);
  671. },
  672. /**
  673. * Handles the click event for removing a module in the editor from the rule
  674. */
  675. clickRemoveModule() {
  676. const module = this.editor.module;
  677. this.removeModule(module);
  678. },
  679. /**
  680. * Clears the editor
  681. */
  682. clearEditor() {
  683. this.preventEditorLoss();
  684. this.editor.module = null;
  685. this.editor.previousState = null;
  686. },
  687. /**
  688. * Saves the module in the editor to customModules array
  689. */
  690. saveEditor() {
  691. this.addCustomModule(this.editor.module);
  692. this.setEditorPreviousState(this.editor.module);
  693. },
  694. // config methods =========================================================
  695. /**
  696. * Add custom config entry to the module
  697. */
  698. addConfig() {
  699. const k = document.getElementById("newConfigKey").value;
  700. const v = document.getElementById("newConfigValue").value;
  701. this.editor.module.config[k] = v;
  702. this.resetNewConfigInputs();
  703. },
  704. /**
  705. * Removes the config entry from the module
  706. */
  707. removeConfig(key) {
  708. delete this.editor.module.config[key];
  709. },
  710. // custom module methods ==================================================
  711. /**
  712. * Adds a module to the customModules array
  713. * @param {Object} module the module to add to the customModules array
  714. */
  715. addCustomModule(module) {
  716. // if module is not in customModules, add it
  717. if (!this.customModules.includes(module)) {
  718. this.customModules.unshift(module);
  719. }
  720. },
  721. /**
  722. * Creates a new module, sets a default name, and adds it to the editor
  723. */
  724. newCustomModule() {
  725. const module = this.newModule();
  726. module.name = 'New Module';
  727. module.config = {};
  728. this.resetNewConfigInputs();
  729. this.addToEditor(module);
  730. },
  731. resetNewConfigInputs() {
  732. document.getElementById("newConfigKey").value = "Configuration";
  733. document.getElementById("newConfigValue").value = "Value";
  734. },
  735. /**
  736. * Removes a module from the customModules array
  737. * @param {Object} module the module to remove from the customModules array
  738. */
  739. removeCustomModule(module) {
  740. this.confirm("are you sure you want to remove this custom module?");
  741. const index = this.customModules.indexOf(module);
  742. this.customModules.splice(index, 1);
  743. },
  744. /**
  745. * Handles confirmation messages for users
  746. * @param {String} msg the message to display in the confirm dialog
  747. */
  748. // TODO: add a confirm dialog and return boolean based on user input
  749. confirm(msg) {
  750. console.log(msg);
  751. },
  752. /**
  753. * Handles click event for publishing the rule
  754. */
  755. handleClickPublish() {
  756. // Confirm user knows what they're getting into
  757. if (!localStorage.getItem('userEmail')) {
  758. alert('Please login first to publish this rule')
  759. return;
  760. }
  761. if (!confirm("Publish to the public Library?")) return;
  762. if (!this.rule.name) {
  763. alert("Please enter a name for this rule.");
  764. return;
  765. }
  766. if (this.rule.modules.length < 1) {
  767. alert("Please add at least one module to this rule.");
  768. return;
  769. }
  770. this.publishing = true;
  771. const rule = this.ruleExport;
  772. var ruleID = new Date().getTime(); // TODO: allow for custom named IDs, check for uniqueness
  773. if (this.edit) {
  774. ruleID = this.rule.ruleID;
  775. }
  776. var latest_ver = 1;
  777. if (this.edit) {
  778. latest_ver = parseInt(this.rule.latest_version) + 1;
  779. }
  780. var previousListVersion = "";
  781. if (this.edit) {
  782. previousListVersion = this.rule.list
  783. } else {
  784. previousListVersion = ruleID + "@" + rule.name + ":" + this.rule.list;
  785. }
  786. // ------------------ exisituing code ---------------
  787. // add to database
  788. // const store = new SteinStore(
  789. // this.steinAPI
  790. // );
  791. // store.append('rules', [{
  792. // ruleID: ruleID,
  793. // timestamp: rule.timestamp,
  794. // icon: rule.icon,
  795. // name: rule.name,
  796. // lineage: rule.lineage,
  797. // summary: rule.summary,
  798. // config: this.jsonify(rule.config),
  799. // modules: this.jsonify(rule.modules),
  800. // creatorName: rule.creator.name,
  801. // creatorUrl: rule.creator.url,
  802. // version: 3
  803. // }]).then(data => {
  804. // this.publishing = false;
  805. // window.open("/create/?r=" + ruleID, "_self", false);
  806. // });
  807. // -=---------------------------- updated code -------------------
  808. const requestData = {
  809. ruleID: ruleID,
  810. timestamp: rule.timestamp,
  811. icon: rule.icon,
  812. name: rule.name,
  813. lineage: rule.lineage,
  814. summary: rule.summary,
  815. config: this.jsonify(rule.config),
  816. modules: this.jsonify(rule.modules),
  817. creatorName: rule.creator.name,
  818. creatorUrl: rule.creator.url,
  819. email: localStorage.getItem('userEmail'),
  820. edit: this.edit,
  821. version: 3,
  822. latest_version: latest_ver,
  823. list: previousListVersion
  824. }
  825. fetch(this.backendUrl, {
  826. method: 'POST',
  827. headers: {
  828. 'Content-Type': 'application/json',
  829. 'Access-Control-Allow-Methods': 'POST',
  830. 'Access-Control-Allow-Headers': 'Content-Type'
  831. // Add any other headers you may need, such as authorization headers
  832. },
  833. body: JSON.stringify(requestData),
  834. }).then(response => {
  835. if (!response.ok) {
  836. throw new Error(`HTTP error! Status: ${response.status}`);
  837. }
  838. return response.json(); // or response.text() if expecting plain text
  839. }).then(data => {
  840. // Handle the data received from the backend
  841. }).then(data => {
  842. this.publishing = false;
  843. window.open("/create/?r=" + ruleID, "_self", false);
  844. }).catch(error => {
  845. // Handle errors that occurred during the fetch
  846. console.error('Fetch error:', error);
  847. });
  848. },
  849. /**
  850. * Handles the click event for downloading the rule as a Markdown file
  851. * Creates a YAML string of the rule
  852. * Then adds it to the bottom of a markdown file
  853. * created from the #rule-export html element
  854. */
  855. handleClickDownload() {
  856. const yaml = jsyaml.dump(this.ruleExport);
  857. const turndown = new TurndownService();
  858. const html = document.getElementById('rule-export');
  859. if (!html) return;
  860. const markdown = turndown.turndown(html);
  861. const output = markdown + '\n\n----\n```yaml\n' + yaml + '\n```';
  862. this.saveFile(`${this.ruleExport.ruleID}.md`, output, 'text/markdown');
  863. },
  864. /**
  865. * IE10+ Firefox, and Chrome method for saving a file
  866. * https://stackoverflow.com/a/33542499
  867. * @param {String} filename name of the file to save
  868. * @param {String} data data to save into a file
  869. * @param {String} type MIME type of the file
  870. */
  871. saveFile(filename, data, type) {
  872. const blob = new Blob([data], { type: type });
  873. if (window.navigator.msSaveOrOpenBlob) {
  874. window.navigator.msSaveBlob(blob, filename);
  875. }
  876. else {
  877. const elem = window.document.createElement('a');
  878. elem.href = window.URL.createObjectURL(blob);
  879. elem.download = filename;
  880. document.body.appendChild(elem);
  881. elem.click();
  882. document.body.removeChild(elem);
  883. }
  884. },
  885. /**
  886. * Handles the click event for importing a rule from a JSON file
  887. */
  888. handleClickImport() {
  889. },
  890. // utility methods ===========================================================
  891. /**
  892. * Takes an html element and finds the closest node (inclusive) that has a data-module-id attribute
  893. * @param {Node} el the html element to check
  894. * @returns {Node} the closest node with a data-module-id attribute
  895. */
  896. getClosestModule(el) {
  897. const parent = el.closest('[data-module-id]');
  898. if (!parent) return false;
  899. if (!parent.module) return false;
  900. return parent;
  901. },
  902. /**
  903. * Handles the click event for activating the rule preview
  904. */
  905. clickPreview() {
  906. if (this.template) this.rule.icon = ''; // TODO: find a less hacky way to reset template icons
  907. this.view = false;
  908. this.preview = !this.preview;
  909. },
  910. /**
  911. * Handles the click event for activating the rule preview for edit rule
  912. */
  913. clickPreviewEdit() {
  914. if (this.template) this.rule.icon = ''; // TODO: find a less hacky way to reset template icons
  915. this.view = false;
  916. this.preview = !this.preview;
  917. this.edit = true;
  918. },
  919. /**
  920. * Filters module library based on the search term
  921. * @param {String} type the name of the type to filter
  922. * @returns {Array} the filtered module library
  923. */
  924. getModulesByType(type) {
  925. return this.modules.filter(module => module.type === type)
  926. },
  927. /**
  928. * Slugifies a string
  929. * https://gist.github.com/codeguy/6684588 (one of the comments)
  930. * @param {String} string the string to slugify
  931. * @returns
  932. */
  933. slugify(string) {
  934. const separator = '-';
  935. return string
  936. .toString()
  937. .normalize('NFD') // split an accented letter in the base letter and the accent
  938. .replace(/[\u0300-\u036f]/g, '') // remove all previously split accents
  939. .toLowerCase()
  940. .replace(/[^a-z0-9 -]/g, '') // remove all chars not letters, numbers and spaces (to be replaced)
  941. .trim()
  942. .replace(/\s+/g, separator);
  943. },
  944. /**
  945. * Creates a human readable timestamp string
  946. * @param {String} date optional date to format
  947. * @returns {String} human readable date '2022.4.12 14:44:56 UTC'
  948. */
  949. timesString(date) {
  950. let now = new Date(date);
  951. if (isNaN(now)) now = new Date();
  952. return now.getUTCFullYear() + '.' + (now.getUTCMonth() + 1) + '.' + now.getUTCDate()
  953. + ' ' + now.getUTCHours() + ":" + now.getUTCMinutes() + ":" + now.getUTCSeconds()
  954. + ' UTC';
  955. },
  956. /**
  957. * stringify an Object
  958. * @param {Object} obj
  959. * @returns JSON string
  960. */
  961. jsonify(obj) {
  962. return JSON.stringify(obj, null, 2);
  963. },
  964. /**
  965. * Takes a moduleID and checks if that moduleID is in use
  966. * if so, returns the moduleID with a number appended to it
  967. * @param {String} test the moduleID to test
  968. * @returns {String} the moduleID, or if in use, with a number appended to it
  969. */
  970. getUniqueId(test) {
  971. let id = test;
  972. let i = 0;
  973. while (this.listModuleIds.includes(id)) {
  974. i++;
  975. id = `${test}-${i}`;
  976. }
  977. return id
  978. },
  979. },
  980. });
  981. /**
  982. * The Module Vue Component
  983. */
  984. app.component('module', {
  985. delimiters: ['[[', ']]'],
  986. inject: ['editor'],
  987. props: {
  988. module: {
  989. type: Object,
  990. required: true,
  991. },
  992. inEditor: {
  993. type: Boolean,
  994. default: false,
  995. },
  996. hideSubmodules: {
  997. type: Boolean,
  998. default: false,
  999. }
  1000. },
  1001. data() {
  1002. return {
  1003. defaultIcon: '/assets/tabler_icons/circle-dotted.svg',
  1004. mouseOver: false,
  1005. dragOver: false
  1006. }
  1007. },
  1008. computed: {
  1009. icon() {
  1010. return this.module.icon ? this.module.icon : this.defaultIcon;
  1011. },
  1012. moduleClass() {
  1013. return {
  1014. 'in-editor': this.editor.source == this.module,
  1015. 'mouse-over': this.mouseOver,
  1016. // TODO: when dragging over the icon the drag-over class disappears
  1017. 'drag-over': this.dragOver
  1018. }
  1019. }
  1020. },
  1021. template: `
  1022. <div
  1023. class="module"
  1024. :class="moduleClass"
  1025. .module="module"
  1026. @mouseover.stop="this.mouseOver = true"
  1027. @mouseout="this.mouseOver = false"
  1028. @dragenter.self="this.dragOver = true"
  1029. @dragleave.self="this.dragOver = false"
  1030. @drop.self="this.dragOver = false"
  1031. :data-module-id="module.moduleID"
  1032. >
  1033. <div class="module__icon-wrapper">
  1034. <span class="module__grain"><img src="/assets/tabler_icons/grain.svg"></span>
  1035. <span class="module__icon"><img :src="icon"></span>
  1036. </div>
  1037. [[module.name]]
  1038. <div class="submodules" v-if="!hideSubmodules && module.modules && module.modules.length">
  1039. <module v-for="submodule in module.modules" :module="submodule" draggable="true"></module>
  1040. </div>
  1041. </div>
  1042. `
  1043. })
  1044. /**
  1045. * A non-interactive Module Vue Component
  1046. * Used for displaying the module
  1047. */
  1048. app.component('moduleDisplay', {
  1049. delimiters: ['[[', ']]'],
  1050. props: {
  1051. module: {
  1052. type: Object,
  1053. required: true,
  1054. }
  1055. },
  1056. data() {
  1057. return {
  1058. defaultIcon: '/assets/tabler_icons/circle-dotted.svg'
  1059. }
  1060. },
  1061. computed: {
  1062. icon() {
  1063. return this.module.icon ? this.module.icon : this.defaultIcon;
  1064. }
  1065. },
  1066. template: `
  1067. <div
  1068. class="module"
  1069. .module="module"
  1070. >
  1071. <div class="module__icon-wrapper">
  1072. <span class="module__icon"><img :src="icon"></span>
  1073. </div>
  1074. [[module.name]]
  1075. <div class="submodules" v-if="module.modules && module.modules.length">
  1076. <module-display v-for="submodule in module.modules" :module="submodule"></module-display>
  1077. </div>
  1078. </div>
  1079. `
  1080. })
  1081. /**
  1082. * The Module list Vue Component
  1083. */
  1084. app.component('moduleList', {
  1085. delimiters: ['[[', ']]'],
  1086. props: {
  1087. module: {
  1088. type: Object,
  1089. required: true,
  1090. },
  1091. hideIcon: {
  1092. type: Boolean,
  1093. default: false,
  1094. }
  1095. },
  1096. data() {
  1097. return {
  1098. defaultIcon: '/assets/tabler_icons/circle-dotted.svg'
  1099. }
  1100. },
  1101. computed: {
  1102. icon() {
  1103. return this.module.icon ? this.module.icon : this.defaultIcon;
  1104. }
  1105. },
  1106. template: `
  1107. <li class="module-list-item">
  1108. <span class="module__icon" v-if="!hideIcon"><img :src="icon"> </span><strong>[[module.name]]</strong>: [[module.summary]]
  1109. <span class="module__config">
  1110. <span v-for="(value, key) in module.config">
  1111. <br />[[key]]: [[value]]
  1112. </span>
  1113. </span>
  1114. <ul class="submodules" v-if="module.modules && module.modules.length">
  1115. <module-list v-for="submodule in module.modules" :module="submodule" :hide-icon="hideIcon"></module-list>
  1116. </ul>
  1117. </li>
  1118. `
  1119. })
  1120. /**
  1121. * A simple button Vue Component
  1122. */
  1123. app.component('vueButton', {
  1124. delimiters: ['[[', ']]'],
  1125. props: {
  1126. icon: {
  1127. type: String,
  1128. required: false,
  1129. default: false
  1130. },
  1131. loading: {
  1132. type: Boolean,
  1133. required: false,
  1134. default: false
  1135. }
  1136. },
  1137. computed: {
  1138. classList() {
  1139. return {
  1140. 'has-icon': this.icon,
  1141. 'is-loading': this.loading
  1142. };
  1143. },
  1144. activeIcon() {
  1145. return this.loading ? '/assets/tabler_icons/refresh.svg' : this.icon;
  1146. }
  1147. },
  1148. template: `
  1149. <button class="btn" :class="classList"><img :src="activeIcon" v-if="icon"> <slot>Click Here</slot></button>
  1150. `
  1151. })
  1152. /**
  1153. * A icon Vue Component
  1154. */
  1155. app.component('icon', {
  1156. delimiters: ['[[', ']]'],
  1157. props: {
  1158. icon: {
  1159. type: String,
  1160. required: true,
  1161. default: '/assets/tabler_icons/circle-dotted.svg'
  1162. }
  1163. },
  1164. template: `
  1165. <span class="icon"><img :src="icon"></span>
  1166. `
  1167. })
  1168. /**
  1169. * Mounts the app to the DOM element with the id 'app'
  1170. */
  1171. vm = app.mount('#app')
  1172. /**
  1173. * Legacy functions for displaying old rules
  1174. */
  1175. // Turns RuleBuilder contents into an output-ready nested array
  1176. // Returns empty array if no modules
  1177. function builderArray() {
  1178. var modules = document.getElementById("module-input").children;
  1179. // takes an array of children
  1180. // returns an array with all modules in the array, recursively nested
  1181. function iterateArray(childs) {
  1182. var moduleArray = [];
  1183. if (childs.length > 0) {
  1184. for (var i = 0; i < childs.length; i++) {
  1185. module = childs[i];
  1186. if (module.classList[0] == "module") {
  1187. var moduleName = module.children.item("module-name");
  1188. var moduleData = moduleName.title;
  1189. var moduleChilds = module.children;
  1190. moduleArray.push(
  1191. [stripHTML(moduleName.innerHTML),
  1192. stripHTML(moduleData),
  1193. iterateArray(moduleChilds)]);
  1194. }
  1195. }
  1196. }
  1197. return moduleArray;
  1198. } // end function
  1199. return iterateArray(modules);
  1200. }
  1201. // returns HTML version of Builder content
  1202. function displayBuilderHTML() {
  1203. var output = "";
  1204. var mainArray = builderArray();
  1205. function arrayHTML(thisArray) {
  1206. var thisOutput = "";
  1207. if (thisArray.length > 0) {
  1208. thisOutput += '<ul>\n';
  1209. for (var i = 0; i < thisArray.length; i++) {
  1210. var item = thisArray[i];
  1211. thisOutput += '<li><strong>' + item[0] + '</strong> ';
  1212. thisOutput += item[1] + '</li>\n';
  1213. if (item[2].length > 0) {
  1214. thisOutput += arrayHTML(item[2]);
  1215. }
  1216. }
  1217. thisOutput += '</ul>\n';
  1218. }
  1219. return thisOutput
  1220. }
  1221. if (mainArray.length > 0) {
  1222. output += '<div class="builder-list">\n';
  1223. output += arrayHTML(mainArray) + '\n</div>\n';
  1224. }
  1225. document.getElementById("builder-field").innerHTML = output;
  1226. }
  1227. // Removes all HTML content, replacing line break tags with newlines
  1228. function stripHTML(input) {
  1229. input = input.replace(/<br ?\/?>/ig, "\n").replace(/(<([^>]+)>)/ig, '');
  1230. return input;
  1231. }