vue.rules.js 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320
  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: '/api/publish_rule',
  50. backendUrlrule: '/api/get_rule',
  51. backedDeleterule: '/api/delete_rule',
  52. adminMail: "medlab@colorado.edu",
  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. var resultArray = ''
  489. if (rule.list != null) {
  490. const splitArray = rule.list.split(':');
  491. resultArray = splitArray.filter(value => value.trim() !== '');
  492. }
  493. var forkedOrNot = 0
  494. if (resultArray.length == 1) {
  495. forkedOrNot = 1;
  496. }
  497. this.rule = {
  498. ruleID: rule.rule_id,
  499. timestamp: rule.time_stamp,
  500. icon: rule.icon,
  501. name: rule.name,
  502. lineage: rule.lineage,
  503. summary: rule.summary,
  504. config: rule.config,
  505. creator: {
  506. name: rule.creator_name,
  507. url: rule.creator_url,
  508. },
  509. modules: (rule.modules) ? JSON.parse(rule.modules) : [],
  510. latest_version: rule.latest_version,
  511. list: rule.list,
  512. forked: forkedOrNot,
  513. deleted: rule.deleted,
  514. edit_history: resultArray
  515. }
  516. if (rule.email == localStorage.getItem('userEmail')) {
  517. this.isOwner = true;
  518. this.isAdmin = true; // this will allow the user to delete his own rules
  519. }
  520. if (localStorage.getItem('userEmail') == this.adminMail) {
  521. this.isAdmin = true;
  522. }
  523. /** Add name to <title> for v3+ rules */
  524. document.title = rule.name + " / CommunityRule"
  525. this.loading = false;
  526. })();
  527. /*fetch(backendUrlGetRule, {
  528. method: 'GET',
  529. headers: {
  530. 'Content-Type': 'application/json',
  531. // Add any other headers you may need, such as authorization headers
  532. },
  533. }).then(response => {
  534. if (!response.ok) {
  535. throw new Error('Network response was not ok');
  536. }
  537. return response.json(); // This returns another Promise
  538. }).then (data => {
  539. var rule = [];
  540. if (data.rules.length > 0) {
  541. rule = data.rules;
  542. }
  543. // no rule found, exit
  544. // TODO: inform the user that the rule was not found
  545. if (!rule) {
  546. this.loading = false;
  547. return;
  548. }
  549. // if this is a legacy (pre-v3) set it as such
  550. if (rule.version < 3) {
  551. this.loading = false;
  552. this.legacy = true;
  553. this.rule = rule;
  554. Vue.nextTick(() => {
  555. if (rule.version == 2) displayBuilderHTML();
  556. });
  557. return;
  558. }
  559. this.rule = {
  560. ruleID: rule.ruleID,
  561. timestamp: rule.timestamp,
  562. icon: rule.icon,
  563. name: rule.name,
  564. lineage: rule.lineage,
  565. summary: rule.summary,
  566. config: rule.config,
  567. creator: {
  568. name: rule.creatorName,
  569. url: rule.creatorUrl,
  570. },
  571. modules: (rule.modules) ? JSON.parse(rule.modules) : []
  572. }
  573. document.title = rule.name + " / CommunityRule"
  574. this.loading = false;
  575. }); */
  576. },
  577. getRuleLink(ruleId) {
  578. // Further split each part based on '@'
  579. const subParts = ruleId.split('@');
  580. // Use the desired sub-part in your link construction
  581. // For example, if you want the first sub-part after splitting on '@'
  582. const finalPart = subParts[0];
  583. return `/create/?r=${finalPart}`;
  584. },
  585. getRuleName(ruleId) {
  586. // Further split each part based on '@'
  587. const subParts = ruleId.split('@');
  588. // Use the desired sub-part in your link construction
  589. // For example, if you want the first sub-part after splitting on '@'
  590. const ruleName = subParts[1];
  591. return ruleName
  592. },
  593. // editor methods =========================================================
  594. clickDelete() {
  595. (async () => {
  596. // read values from all sheets
  597. const requestData = {
  598. ruleID: this.rule.ruleID
  599. }
  600. await fetch(this.backedDeleterule, {
  601. method: 'DELETE',
  602. headers: {
  603. 'Content-Type': 'application/json',
  604. // Add any other headers you may need, such as authorization headers
  605. },
  606. body: JSON.stringify(requestData),
  607. }).then(response => {
  608. if (!response.ok) {
  609. alert("Error while deleting rule");
  610. throw new Error('Network response was not ok');
  611. }
  612. return response.json(); // This returns another Promise
  613. }).then(data => {
  614. alert('Rule deleted successfully');
  615. window.open("/library", false);
  616. });
  617. this.loading = false;
  618. })();
  619. },
  620. /**
  621. * Adds a module to the editor
  622. * @param {Object} module the module to add to the editor
  623. */
  624. addToEditor(module) {
  625. this.preventEditorLoss();
  626. this.setEditorSource(module);
  627. this.setEditorPreviousState(module);
  628. this.editor.module = module;
  629. },
  630. /**
  631. * Copies a module to the editor
  632. * @param {Object} module the module to copy to the editor
  633. */
  634. copyToEditor(module) {
  635. const moduleCopy = this.cloneModule(module);
  636. this.preventEditorLoss();
  637. this.setEditorSource(module);
  638. this.setEditorPreviousState(moduleCopy);
  639. this.editor.module = moduleCopy;
  640. },
  641. /**
  642. * Takes a module and clones it into the editor.previousState
  643. * @param {Object} module the module to add to the previous state
  644. */
  645. setEditorPreviousState(module) {
  646. this.editor.previousState = { ...module };
  647. },
  648. /**
  649. * Sets the editor.source to the module
  650. * @param {Object} module the module to set the editor source to
  651. */
  652. setEditorSource(module) {
  653. this.editor.source = module;
  654. },
  655. /**
  656. * Checks if the editor has edits and that the current module in the editor is not present in the rule
  657. * If the module in the editor would be lost, confirm with the user
  658. * then adds the module to the customModules array
  659. */
  660. preventEditorLoss() {
  661. // if the editor has changes and the module isn't in the rule, save it to the custom modules
  662. if (this.editorHasEdits && !this.moduleContains(this.editor.module)) {
  663. this.confirm('You have unsaved changes. Are you sure you want to discard them?')
  664. this.addCustomModule(this.editor.module);
  665. }
  666. },
  667. /**
  668. * Handles the click event for adding a module from the editor to the rule
  669. */
  670. clickAddModule() {
  671. const module = this.editor.module;
  672. this.addModule(module);
  673. this.addToEditor(module);
  674. },
  675. /**
  676. * Handles the click event for removing a module in the editor from the rule
  677. */
  678. clickRemoveModule() {
  679. const module = this.editor.module;
  680. this.removeModule(module);
  681. },
  682. /**
  683. * Clears the editor
  684. */
  685. clearEditor() {
  686. this.preventEditorLoss();
  687. this.editor.module = null;
  688. this.editor.previousState = null;
  689. },
  690. /**
  691. * Saves the module in the editor to customModules array
  692. */
  693. saveEditor() {
  694. this.addCustomModule(this.editor.module);
  695. this.setEditorPreviousState(this.editor.module);
  696. },
  697. // config methods =========================================================
  698. /**
  699. * Add custom config entry to the module
  700. */
  701. addConfig() {
  702. const k = document.getElementById("newConfigKey").value;
  703. const v = document.getElementById("newConfigValue").value;
  704. this.editor.module.config[k] = v;
  705. this.resetNewConfigInputs();
  706. },
  707. /**
  708. * Removes the config entry from the module
  709. */
  710. removeConfig(key) {
  711. delete this.editor.module.config[key];
  712. },
  713. // custom module methods ==================================================
  714. /**
  715. * Adds a module to the customModules array
  716. * @param {Object} module the module to add to the customModules array
  717. */
  718. addCustomModule(module) {
  719. // if module is not in customModules, add it
  720. if (!this.customModules.includes(module)) {
  721. this.customModules.unshift(module);
  722. }
  723. },
  724. /**
  725. * Creates a new module, sets a default name, and adds it to the editor
  726. */
  727. newCustomModule() {
  728. const module = this.newModule();
  729. module.name = 'New Module';
  730. module.config = {};
  731. this.resetNewConfigInputs();
  732. this.addToEditor(module);
  733. },
  734. resetNewConfigInputs() {
  735. document.getElementById("newConfigKey").value = "Configuration";
  736. document.getElementById("newConfigValue").value = "Value";
  737. },
  738. /**
  739. * Removes a module from the customModules array
  740. * @param {Object} module the module to remove from the customModules array
  741. */
  742. removeCustomModule(module) {
  743. this.confirm("are you sure you want to remove this custom module?");
  744. const index = this.customModules.indexOf(module);
  745. this.customModules.splice(index, 1);
  746. },
  747. /**
  748. * Handles confirmation messages for users
  749. * @param {String} msg the message to display in the confirm dialog
  750. */
  751. // TODO: add a confirm dialog and return boolean based on user input
  752. confirm(msg) {
  753. console.log(msg);
  754. },
  755. /**
  756. * Handles click event for publishing the rule
  757. */
  758. handleClickPublish() {
  759. // Confirm user knows what they're getting into
  760. if (!localStorage.getItem('userEmail')) {
  761. alert('Please login first to publish this rule')
  762. return;
  763. }
  764. if (!confirm("Publish to the public Library?")) return;
  765. if (!this.rule.name) {
  766. alert("Please enter a name for this rule.");
  767. return;
  768. }
  769. if (this.rule.modules.length < 1) {
  770. alert("Please add at least one module to this rule.");
  771. return;
  772. }
  773. this.publishing = true;
  774. const rule = this.ruleExport;
  775. var ruleID = new Date().getTime(); // TODO: allow for custom named IDs, check for uniqueness
  776. if (this.edit) {
  777. ruleID = this.rule.ruleID;
  778. }
  779. var latest_ver = 1;
  780. if (this.edit) {
  781. latest_ver = parseInt(this.rule.latest_version) + 1;
  782. }
  783. var previousListVersion = "";
  784. if (this.edit) {
  785. previousListVersion = this.rule.list
  786. } else {
  787. previousListVersion = ruleID + "@" + rule.name + ":" + this.rule.list;
  788. }
  789. // ------------------ exisituing code ---------------
  790. // add to database
  791. // const store = new SteinStore(
  792. // this.steinAPI
  793. // );
  794. // store.append('rules', [{
  795. // ruleID: ruleID,
  796. // timestamp: rule.timestamp,
  797. // icon: rule.icon,
  798. // name: rule.name,
  799. // lineage: rule.lineage,
  800. // summary: rule.summary,
  801. // config: this.jsonify(rule.config),
  802. // modules: this.jsonify(rule.modules),
  803. // creatorName: rule.creator.name,
  804. // creatorUrl: rule.creator.url,
  805. // version: 3
  806. // }]).then(data => {
  807. // this.publishing = false;
  808. // window.open("/create/?r=" + ruleID, "_self", false);
  809. // });
  810. // -=---------------------------- updated code -------------------
  811. const requestData = {
  812. ruleID: ruleID,
  813. timestamp: rule.timestamp,
  814. icon: rule.icon,
  815. name: rule.name,
  816. lineage: rule.lineage,
  817. summary: rule.summary,
  818. config: this.jsonify(rule.config),
  819. modules: this.jsonify(rule.modules),
  820. creatorName: rule.creator.name,
  821. creatorUrl: rule.creator.url,
  822. email: localStorage.getItem('userEmail'),
  823. edit: this.edit,
  824. version: 3,
  825. latest_version: latest_ver,
  826. list: previousListVersion
  827. }
  828. fetch(this.backendUrl, {
  829. method: 'POST',
  830. headers: {
  831. 'Content-Type': 'application/json',
  832. 'Access-Control-Allow-Methods': 'POST',
  833. 'Access-Control-Allow-Headers': 'Content-Type'
  834. // Add any other headers you may need, such as authorization headers
  835. },
  836. body: JSON.stringify(requestData),
  837. }).then(response => {
  838. if (!response.ok) {
  839. throw new Error(`HTTP error! Status: ${response.status}`);
  840. }
  841. return response.json(); // or response.text() if expecting plain text
  842. }).then(data => {
  843. // Handle the data received from the backend
  844. }).then(data => {
  845. this.publishing = false;
  846. window.open("/create/?r=" + ruleID, "_self", false);
  847. }).catch(error => {
  848. // Handle errors that occurred during the fetch
  849. console.error('Fetch error:', error);
  850. });
  851. },
  852. /**
  853. * Handles the click event for downloading the rule as a Markdown file
  854. * Creates a YAML string of the rule
  855. * Then adds it to the bottom of a markdown file
  856. * created from the #rule-export html element
  857. */
  858. handleClickDownload() {
  859. const yaml = jsyaml.dump(this.ruleExport);
  860. const turndown = new TurndownService();
  861. const html = document.getElementById('rule-export');
  862. if (!html) return;
  863. const markdown = turndown.turndown(html);
  864. const output = markdown + '\n\n----\n```yaml\n' + yaml + '\n```';
  865. this.saveFile(`${this.ruleExport.ruleID}.md`, output, 'text/markdown');
  866. },
  867. /**
  868. * IE10+ Firefox, and Chrome method for saving a file
  869. * https://stackoverflow.com/a/33542499
  870. * @param {String} filename name of the file to save
  871. * @param {String} data data to save into a file
  872. * @param {String} type MIME type of the file
  873. */
  874. saveFile(filename, data, type) {
  875. const blob = new Blob([data], { type: type });
  876. if (window.navigator.msSaveOrOpenBlob) {
  877. window.navigator.msSaveBlob(blob, filename);
  878. }
  879. else {
  880. const elem = window.document.createElement('a');
  881. elem.href = window.URL.createObjectURL(blob);
  882. elem.download = filename;
  883. document.body.appendChild(elem);
  884. elem.click();
  885. document.body.removeChild(elem);
  886. }
  887. },
  888. /**
  889. * Handles the click event for importing a rule from a JSON file
  890. */
  891. handleClickImport() {
  892. },
  893. // utility methods ===========================================================
  894. /**
  895. * Takes an html element and finds the closest node (inclusive) that has a data-module-id attribute
  896. * @param {Node} el the html element to check
  897. * @returns {Node} the closest node with a data-module-id attribute
  898. */
  899. getClosestModule(el) {
  900. const parent = el.closest('[data-module-id]');
  901. if (!parent) return false;
  902. if (!parent.module) return false;
  903. return parent;
  904. },
  905. /**
  906. * Handles the click event for activating the rule preview
  907. */
  908. clickPreview() {
  909. if (this.template) this.rule.icon = ''; // TODO: find a less hacky way to reset template icons
  910. this.view = false;
  911. this.preview = !this.preview;
  912. },
  913. /**
  914. * Handles the click event for activating the rule preview for edit rule
  915. */
  916. clickPreviewEdit() {
  917. if (this.template) this.rule.icon = ''; // TODO: find a less hacky way to reset template icons
  918. this.view = false;
  919. this.preview = !this.preview;
  920. this.edit = true;
  921. },
  922. /**
  923. * Filters module library based on the search term
  924. * @param {String} type the name of the type to filter
  925. * @returns {Array} the filtered module library
  926. */
  927. getModulesByType(type) {
  928. return this.modules.filter(module => module.type === type)
  929. },
  930. /**
  931. * Slugifies a string
  932. * https://gist.github.com/codeguy/6684588 (one of the comments)
  933. * @param {String} string the string to slugify
  934. * @returns
  935. */
  936. slugify(string) {
  937. const separator = '-';
  938. return string
  939. .toString()
  940. .normalize('NFD') // split an accented letter in the base letter and the accent
  941. .replace(/[\u0300-\u036f]/g, '') // remove all previously split accents
  942. .toLowerCase()
  943. .replace(/[^a-z0-9 -]/g, '') // remove all chars not letters, numbers and spaces (to be replaced)
  944. .trim()
  945. .replace(/\s+/g, separator);
  946. },
  947. /**
  948. * Creates a human readable timestamp string
  949. * @param {String} date optional date to format
  950. * @returns {String} human readable date '2022.4.12 14:44:56 UTC'
  951. */
  952. timesString(date) {
  953. let now = new Date(date);
  954. if (isNaN(now)) now = new Date();
  955. return now.getUTCFullYear() + '.' + (now.getUTCMonth() + 1) + '.' + now.getUTCDate()
  956. + ' ' + now.getUTCHours() + ":" + now.getUTCMinutes() + ":" + now.getUTCSeconds()
  957. + ' UTC';
  958. },
  959. /**
  960. * stringify an Object
  961. * @param {Object} obj
  962. * @returns JSON string
  963. */
  964. jsonify(obj) {
  965. return JSON.stringify(obj, null, 2);
  966. },
  967. /**
  968. * Takes a moduleID and checks if that moduleID is in use
  969. * if so, returns the moduleID with a number appended to it
  970. * @param {String} test the moduleID to test
  971. * @returns {String} the moduleID, or if in use, with a number appended to it
  972. */
  973. getUniqueId(test) {
  974. let id = test;
  975. let i = 0;
  976. while (this.listModuleIds.includes(id)) {
  977. i++;
  978. id = `${test}-${i}`;
  979. }
  980. return id
  981. },
  982. },
  983. });
  984. /**
  985. * The Module Vue Component
  986. */
  987. app.component('module', {
  988. delimiters: ['[[', ']]'],
  989. inject: ['editor'],
  990. props: {
  991. module: {
  992. type: Object,
  993. required: true,
  994. },
  995. inEditor: {
  996. type: Boolean,
  997. default: false,
  998. },
  999. hideSubmodules: {
  1000. type: Boolean,
  1001. default: false,
  1002. }
  1003. },
  1004. data() {
  1005. return {
  1006. defaultIcon: '/assets/tabler_icons/circle-dotted.svg',
  1007. mouseOver: false,
  1008. dragOver: false
  1009. }
  1010. },
  1011. computed: {
  1012. icon() {
  1013. return this.module.icon ? this.module.icon : this.defaultIcon;
  1014. },
  1015. moduleClass() {
  1016. return {
  1017. 'in-editor': this.editor.source == this.module,
  1018. 'mouse-over': this.mouseOver,
  1019. // TODO: when dragging over the icon the drag-over class disappears
  1020. 'drag-over': this.dragOver
  1021. }
  1022. }
  1023. },
  1024. template: `
  1025. <div
  1026. class="module"
  1027. :class="moduleClass"
  1028. .module="module"
  1029. @mouseover.stop="this.mouseOver = true"
  1030. @mouseout="this.mouseOver = false"
  1031. @dragenter.self="this.dragOver = true"
  1032. @dragleave.self="this.dragOver = false"
  1033. @drop.self="this.dragOver = false"
  1034. :data-module-id="module.moduleID"
  1035. >
  1036. <div class="module__icon-wrapper">
  1037. <span class="module__grain"><img src="/assets/tabler_icons/grain.svg"></span>
  1038. <span class="module__icon"><img :src="icon"></span>
  1039. </div>
  1040. [[module.name]]
  1041. <div class="submodules" v-if="!hideSubmodules && module.modules && module.modules.length">
  1042. <module v-for="submodule in module.modules" :module="submodule" draggable="true"></module>
  1043. </div>
  1044. </div>
  1045. `
  1046. })
  1047. /**
  1048. * A non-interactive Module Vue Component
  1049. * Used for displaying the module
  1050. */
  1051. app.component('moduleDisplay', {
  1052. delimiters: ['[[', ']]'],
  1053. props: {
  1054. module: {
  1055. type: Object,
  1056. required: true,
  1057. }
  1058. },
  1059. data() {
  1060. return {
  1061. defaultIcon: '/assets/tabler_icons/circle-dotted.svg'
  1062. }
  1063. },
  1064. computed: {
  1065. icon() {
  1066. return this.module.icon ? this.module.icon : this.defaultIcon;
  1067. }
  1068. },
  1069. template: `
  1070. <div
  1071. class="module"
  1072. .module="module"
  1073. >
  1074. <div class="module__icon-wrapper">
  1075. <span class="module__icon"><img :src="icon"></span>
  1076. </div>
  1077. [[module.name]]
  1078. <div class="submodules" v-if="module.modules && module.modules.length">
  1079. <module-display v-for="submodule in module.modules" :module="submodule"></module-display>
  1080. </div>
  1081. </div>
  1082. `
  1083. })
  1084. /**
  1085. * The Module list Vue Component
  1086. */
  1087. app.component('moduleList', {
  1088. delimiters: ['[[', ']]'],
  1089. props: {
  1090. module: {
  1091. type: Object,
  1092. required: true,
  1093. },
  1094. hideIcon: {
  1095. type: Boolean,
  1096. default: false,
  1097. }
  1098. },
  1099. data() {
  1100. return {
  1101. defaultIcon: '/assets/tabler_icons/circle-dotted.svg'
  1102. }
  1103. },
  1104. computed: {
  1105. icon() {
  1106. return this.module.icon ? this.module.icon : this.defaultIcon;
  1107. }
  1108. },
  1109. template: `
  1110. <li class="module-list-item">
  1111. <span class="module__icon" v-if="!hideIcon"><img :src="icon"> </span><strong>[[module.name]]</strong>: [[module.summary]]
  1112. <span class="module__config">
  1113. <span v-for="(value, key) in module.config">
  1114. <br />[[key]]: [[value]]
  1115. </span>
  1116. </span>
  1117. <ul class="submodules" v-if="module.modules && module.modules.length">
  1118. <module-list v-for="submodule in module.modules" :module="submodule" :hide-icon="hideIcon"></module-list>
  1119. </ul>
  1120. </li>
  1121. `
  1122. })
  1123. /**
  1124. * A simple button Vue Component
  1125. */
  1126. app.component('vueButton', {
  1127. delimiters: ['[[', ']]'],
  1128. props: {
  1129. icon: {
  1130. type: String,
  1131. required: false,
  1132. default: false
  1133. },
  1134. loading: {
  1135. type: Boolean,
  1136. required: false,
  1137. default: false
  1138. }
  1139. },
  1140. computed: {
  1141. classList() {
  1142. return {
  1143. 'has-icon': this.icon,
  1144. 'is-loading': this.loading
  1145. };
  1146. },
  1147. activeIcon() {
  1148. return this.loading ? '/assets/tabler_icons/refresh.svg' : this.icon;
  1149. }
  1150. },
  1151. template: `
  1152. <button class="btn" :class="classList"><img :src="activeIcon" v-if="icon"> <slot>Click Here</slot></button>
  1153. `
  1154. })
  1155. /**
  1156. * A icon Vue Component
  1157. */
  1158. app.component('icon', {
  1159. delimiters: ['[[', ']]'],
  1160. props: {
  1161. icon: {
  1162. type: String,
  1163. required: true,
  1164. default: '/assets/tabler_icons/circle-dotted.svg'
  1165. }
  1166. },
  1167. template: `
  1168. <span class="icon"><img :src="icon"></span>
  1169. `
  1170. })
  1171. /**
  1172. * Mounts the app to the DOM element with the id 'app'
  1173. */
  1174. vm = app.mount('#app')
  1175. /**
  1176. * Legacy functions for displaying old rules
  1177. */
  1178. // Turns RuleBuilder contents into an output-ready nested array
  1179. // Returns empty array if no modules
  1180. function builderArray() {
  1181. var modules = document.getElementById("module-input").children;
  1182. // takes an array of children
  1183. // returns an array with all modules in the array, recursively nested
  1184. function iterateArray(childs) {
  1185. var moduleArray = [];
  1186. if (childs.length > 0) {
  1187. for (var i = 0; i < childs.length; i++) {
  1188. module = childs[i];
  1189. if (module.classList[0] == "module") {
  1190. var moduleName = module.children.item("module-name");
  1191. var moduleData = moduleName.title;
  1192. var moduleChilds = module.children;
  1193. moduleArray.push(
  1194. [stripHTML(moduleName.innerHTML),
  1195. stripHTML(moduleData),
  1196. iterateArray(moduleChilds)]);
  1197. }
  1198. }
  1199. }
  1200. return moduleArray;
  1201. } // end function
  1202. return iterateArray(modules);
  1203. }
  1204. // returns HTML version of Builder content
  1205. function displayBuilderHTML() {
  1206. var output = "";
  1207. var mainArray = builderArray();
  1208. function arrayHTML(thisArray) {
  1209. var thisOutput = "";
  1210. if (thisArray.length > 0) {
  1211. thisOutput += '<ul>\n';
  1212. for (var i = 0; i < thisArray.length; i++) {
  1213. var item = thisArray[i];
  1214. thisOutput += '<li><strong>' + item[0] + '</strong> ';
  1215. thisOutput += item[1] + '</li>\n';
  1216. if (item[2].length > 0) {
  1217. thisOutput += arrayHTML(item[2]);
  1218. }
  1219. }
  1220. thisOutput += '</ul>\n';
  1221. }
  1222. return thisOutput
  1223. }
  1224. if (mainArray.length > 0) {
  1225. output += '<div class="builder-list">\n';
  1226. output += arrayHTML(mainArray) + '\n</div>\n';
  1227. }
  1228. document.getElementById("builder-field").innerHTML = output;
  1229. }
  1230. // Removes all HTML content, replacing line break tags with newlines
  1231. function stripHTML(input) {
  1232. input = input.replace(/<br ?\/?>/ig, "\n").replace(/(<([^>]+)>)/ig, '');
  1233. return input;
  1234. }