vue.rules.js 33 KB

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