vue.rules.js 39 KB

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