vue.rules.js 32 KB

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