vue.rules.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  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. /** Add name to <title> for v3+ rules */
  467. document.title = rule.name + " / CommunityRule"
  468. this.loading = false;
  469. })();
  470. },
  471. // editor methods =========================================================
  472. /**
  473. * Adds a module to the editor
  474. * @param {Object} module the module to add to the editor
  475. */
  476. addToEditor(module) {
  477. this.preventEditorLoss();
  478. this.setEditorSource(module);
  479. this.setEditorPreviousState(module);
  480. this.editor.module = module;
  481. },
  482. /**
  483. * Copies a module to the editor
  484. * @param {Object} module the module to copy to the editor
  485. */
  486. copyToEditor(module) {
  487. const moduleCopy = this.cloneModule(module);
  488. this.preventEditorLoss();
  489. this.setEditorSource(module);
  490. this.setEditorPreviousState(moduleCopy);
  491. this.editor.module = moduleCopy;
  492. },
  493. /**
  494. * Takes a module and clones it into the editor.previousState
  495. * @param {Object} module the module to add to the previous state
  496. */
  497. setEditorPreviousState(module) {
  498. this.editor.previousState = { ...module };
  499. },
  500. /**
  501. * Sets the editor.source to the module
  502. * @param {Object} module the module to set the editor source to
  503. */
  504. setEditorSource(module) {
  505. this.editor.source = module;
  506. },
  507. /**
  508. * Checks if the editor has edits and that the current module in the editor is not present in the rule
  509. * If the module in the editor would be lost, confirm with the user
  510. * then adds the module to the customModules array
  511. */
  512. preventEditorLoss() {
  513. // if the editor has changes and the module isn't in the rule, save it to the custom modules
  514. if (this.editorHasEdits && !this.moduleContains(this.editor.module)) {
  515. this.confirm('You have unsaved changes. Are you sure you want to discard them?')
  516. this.addCustomModule(this.editor.module);
  517. }
  518. },
  519. /**
  520. * Handles the click event for adding a module from the editor to the rule
  521. */
  522. clickAddModule() {
  523. const module = this.editor.module;
  524. this.addModule(module);
  525. this.addToEditor(module);
  526. },
  527. /**
  528. * Handles the click event for removing a module in the editor from the rule
  529. */
  530. clickRemoveModule() {
  531. const module = this.editor.module;
  532. this.removeModule(module);
  533. },
  534. /**
  535. * Clears the editor
  536. */
  537. clearEditor() {
  538. this.preventEditorLoss();
  539. this.editor.module = null;
  540. this.editor.previousState = null;
  541. },
  542. /**
  543. * Saves the module in the editor to customModules array
  544. */
  545. saveEditor() {
  546. this.addCustomModule(this.editor.module);
  547. this.setEditorPreviousState(this.editor.module);
  548. },
  549. // custom module methods ==================================================
  550. /**
  551. * Adds a module to the customModules array
  552. * @param {Object} module the module to add to the customModules array
  553. */
  554. addCustomModule(module) {
  555. // if module is not in customModules, add it
  556. if (!this.customModules.includes(module)) {
  557. this.customModules.unshift(module);
  558. }
  559. },
  560. /**
  561. * Creates a new module, set's a default name, and adds it to the editor
  562. */
  563. newCustomModule() {
  564. const module = this.newModule();
  565. module.name = 'New Module';
  566. this.addToEditor(module);
  567. },
  568. /**
  569. * Removes a module from the customModules array
  570. * @param {Object} module the module to remove from the customModules array
  571. */
  572. removeCustomModule(module) {
  573. this.confirm("are you sure you want to remove this custom module?");
  574. const index = this.customModules.indexOf(module);
  575. this.customModules.splice(index, 1);
  576. },
  577. /**
  578. * Handles confirmation messages for users
  579. * @param {String} msg the message to display in the confirm dialog
  580. */
  581. // TODO: add a confirm dialog and return boolean based on user input
  582. confirm(msg) {
  583. console.log(msg);
  584. },
  585. // export and download methods =============================================
  586. /**
  587. * Handles click event for publishing the rule
  588. */
  589. handleClickPublish() {
  590. // Confirm user knows what they're getting into
  591. if (!confirm("Publish to the public Library?")) return;
  592. if ( !this.rule.name ) {
  593. alert("Please enter a name for this rule.");
  594. return;
  595. }
  596. if ( this.rule.modules.length < 1 ) {
  597. alert("Please add at least one module to this rule.");
  598. return;
  599. }
  600. this.publishing = true;
  601. const rule = this.ruleExport;
  602. const ruleID = new Date().getTime(); // TODO: allow for custom named IDs, check for uniqueness
  603. // add to database
  604. const store = new SteinStore(
  605. this.steinAPI
  606. );
  607. store.append('rules', [{
  608. ruleID: ruleID,
  609. timestamp: rule.timestamp,
  610. icon: rule.icon,
  611. name: rule.name,
  612. lineage: rule.lineage,
  613. summary: rule.summary,
  614. modules: this.jsonify(rule.modules),
  615. creatorName: rule.creator.name,
  616. creatorUrl: rule.creator.url,
  617. version: 3
  618. }]).then(data => {
  619. this.publishing = false;
  620. window.open("/create/?r=" + ruleID, "_self", false);
  621. });
  622. },
  623. /**
  624. * Handles the click event for downloading the rule as a Markdown file
  625. * Creates a YAML string of the rule
  626. * Then adds it to the bottom of a markdown file
  627. * created from the #rule-export html element
  628. */
  629. handleClickDownload() {
  630. const yaml = jsyaml.dump(this.ruleExport);
  631. const turndown = new TurndownService();
  632. const html = document.getElementById('rule-export');
  633. if (!html) return;
  634. const markdown = turndown.turndown(html);
  635. const output = markdown + '\n\n----\n```yaml\n' + yaml + '\n```';
  636. this.saveFile(`${this.ruleExport.ruleID}.md`, output, 'text/markdown');
  637. },
  638. /**
  639. * Handles the click event for downloading the rule as a JSON file
  640. */
  641. handleClickExport() {
  642. const output = this.json;
  643. this.saveFile(`${this.ruleExport.ruleID}.json`, output, 'application/json');
  644. },
  645. /**
  646. * IE10+ Firefox, and Chrome method for saving a file
  647. * https://stackoverflow.com/a/33542499
  648. * @param {String} filename name of the file to save
  649. * @param {String} data data to save into a file
  650. * @param {String} type MIME type of the file
  651. */
  652. saveFile(filename, data, type) {
  653. const blob = new Blob([data], { type: type });
  654. if (window.navigator.msSaveOrOpenBlob) {
  655. window.navigator.msSaveBlob(blob, filename);
  656. }
  657. else {
  658. const elem = window.document.createElement('a');
  659. elem.href = window.URL.createObjectURL(blob);
  660. elem.download = filename;
  661. document.body.appendChild(elem);
  662. elem.click();
  663. document.body.removeChild(elem);
  664. }
  665. },
  666. /**
  667. * Handles the click event for importing a rule from a JSON file
  668. */
  669. handleClickImport() {
  670. },
  671. // utility methods ===========================================================
  672. /**
  673. * Takes an html element and finds the closest node (inclusive) that has a data-module-id attribute
  674. * @param {Node} el the html element to check
  675. * @returns {Node} the closest node with a data-module-id attribute
  676. */
  677. getClosestModule(el) {
  678. const parent = el.closest('[data-module-id]');
  679. if (!parent) return false;
  680. if (!parent.module) return false;
  681. return parent;
  682. },
  683. /**
  684. * Handles the click event for activating the rule preview
  685. */
  686. clickPreview() {
  687. if(this.template) this.rule.icon = ''; // TODO: find a less hacky way to reset template icons
  688. this.view = false;
  689. this.preview = !this.preview;
  690. },
  691. /**
  692. * Filters module library based on the search term
  693. * @param {String} type the name of the type to filter
  694. * @returns {Array} the filtered module library
  695. */
  696. getModulesByType(type) {
  697. return this.modules.filter(module => module.type === type)
  698. },
  699. /**
  700. * Slugifies a string
  701. * https://gist.github.com/codeguy/6684588 (one of the comments)
  702. * @param {String} string the string to slugify
  703. * @returns
  704. */
  705. slugify(string) {
  706. const separator = '-';
  707. return string
  708. .toString()
  709. .normalize('NFD') // split an accented letter in the base letter and the accent
  710. .replace(/[\u0300-\u036f]/g, '') // remove all previously split accents
  711. .toLowerCase()
  712. .replace(/[^a-z0-9 -]/g, '') // remove all chars not letters, numbers and spaces (to be replaced)
  713. .trim()
  714. .replace(/\s+/g, separator);
  715. },
  716. /**
  717. * Creates a human readable timestamp string
  718. * @param {String} date optional date to format
  719. * @returns {String} human readable date '2022.4.12 14:44:56 UTC'
  720. */
  721. timesString(date) {
  722. let now = new Date(date);
  723. if (isNaN(now)) now = new Date();
  724. return now.getUTCFullYear() + '.' + (now.getUTCMonth() + 1) + '.' + now.getUTCDate()
  725. + ' ' + now.getUTCHours() + ":" + now.getUTCMinutes() + ":" + now.getUTCSeconds()
  726. + ' UTC';
  727. },
  728. /**
  729. * stringify an Object
  730. * @param {Object} obj
  731. * @returns JSON string
  732. */
  733. jsonify(obj) {
  734. return JSON.stringify(obj, null, 2);
  735. },
  736. /**
  737. * Takes a moduleID and checks if that moduleID is in use
  738. * if so, returns the moduleID with a number appended to it
  739. * @param {String} test the moduleID to test
  740. * @returns {String} the moduleID, or if in use, with a number appended to it
  741. */
  742. getUniqueId(test) {
  743. let id = test;
  744. let i = 0;
  745. while (this.listModuleIds.includes(id)) {
  746. i++;
  747. id = `${test}-${i}`;
  748. }
  749. return id
  750. },
  751. },
  752. });
  753. /**
  754. * The Module Vue Component
  755. */
  756. app.component('module', {
  757. delimiters: ['[[', ']]'],
  758. inject: ['editor'],
  759. props: {
  760. module: {
  761. type: Object,
  762. required: true,
  763. },
  764. inEditor: {
  765. type: Boolean,
  766. default: false,
  767. },
  768. hideSubmodules: {
  769. type: Boolean,
  770. default: false,
  771. }
  772. },
  773. data() {
  774. return {
  775. defaultIcon: '/assets/tabler_icons/circle-dotted.svg',
  776. mouseOver: false,
  777. dragOver: false
  778. }
  779. },
  780. computed: {
  781. icon() {
  782. return this.module.icon ? this.module.icon : this.defaultIcon;
  783. },
  784. moduleClass() {
  785. return {
  786. 'in-editor': this.editor.source == this.module,
  787. 'mouse-over': this.mouseOver,
  788. // TODO: when dragging over the icon the drag-over class disappears
  789. 'drag-over': this.dragOver
  790. }
  791. }
  792. },
  793. template: `
  794. <div
  795. class="module"
  796. :class="moduleClass"
  797. .module="module"
  798. @mouseover.stop="this.mouseOver = true"
  799. @mouseout="this.mouseOver = false"
  800. @dragenter.self="this.dragOver = true"
  801. @dragleave.self="this.dragOver = false"
  802. @drop.self="this.dragOver = false"
  803. :data-module-id="module.moduleID"
  804. >
  805. <div class="module__icon-wrapper">
  806. <span class="module__grain"><img src="/assets/tabler_icons/grain.svg"></span>
  807. <span class="module__icon"><img :src="icon"></span>
  808. </div>
  809. [[module.name]]
  810. <div class="submodules" v-if="!hideSubmodules && module.modules && module.modules.length">
  811. <module v-for="submodule in module.modules" :module="submodule" draggable="true"></module>
  812. </div>
  813. </div>
  814. `
  815. })
  816. /**
  817. * A non-interactive Module Vue Component
  818. * Used for displaying the module
  819. */
  820. app.component('moduleDisplay', {
  821. delimiters: ['[[', ']]'],
  822. props: {
  823. module: {
  824. type: Object,
  825. required: true,
  826. }
  827. },
  828. data() {
  829. return {
  830. defaultIcon: '/assets/tabler_icons/circle-dotted.svg'
  831. }
  832. },
  833. computed: {
  834. icon() {
  835. return this.module.icon ? this.module.icon : this.defaultIcon;
  836. }
  837. },
  838. template: `
  839. <div
  840. class="module"
  841. .module="module"
  842. >
  843. <div class="module__icon-wrapper">
  844. <span class="module__icon"><img :src="icon"></span>
  845. </div>
  846. [[module.name]]
  847. <div class="submodules" v-if="module.modules && module.modules.length">
  848. <module-display v-for="submodule in module.modules" :module="submodule"></module-display>
  849. </div>
  850. </div>
  851. `
  852. })
  853. /**
  854. * The Module list Vue Component
  855. */
  856. app.component('moduleList', {
  857. delimiters: ['[[', ']]'],
  858. props: {
  859. module: {
  860. type: Object,
  861. required: true,
  862. },
  863. hideIcon: {
  864. type: Boolean,
  865. default: false,
  866. }
  867. },
  868. data() {
  869. return {
  870. defaultIcon: '/assets/tabler_icons/circle-dotted.svg'
  871. }
  872. },
  873. computed: {
  874. icon() {
  875. return this.module.icon ? this.module.icon : this.defaultIcon;
  876. }
  877. },
  878. template: `
  879. <li class="module-list-item">
  880. <span class="module__icon" v-if="!hideIcon"><img :src="icon"> </span><strong>[[module.name]]</strong>: [[module.summary]]
  881. <ul class="submodules" v-if="module.modules && module.modules.length">
  882. <module-list v-for="submodule in module.modules" :module="submodule" :hide-icon="hideIcon"></module-list>
  883. </ul>
  884. </li>
  885. `
  886. })
  887. /**
  888. * A simple button Vue Component
  889. */
  890. app.component('vueButton', {
  891. delimiters: ['[[', ']]'],
  892. props: {
  893. icon: {
  894. type: String,
  895. required: false,
  896. default: false
  897. },
  898. loading: {
  899. type: Boolean,
  900. required: false,
  901. default: false
  902. }
  903. },
  904. computed: {
  905. classList() {
  906. return {
  907. 'has-icon': this.icon,
  908. 'is-loading': this.loading
  909. };
  910. },
  911. activeIcon() {
  912. return this.loading ? '/assets/tabler_icons/refresh.svg' : this.icon;
  913. }
  914. },
  915. template: `
  916. <button class="btn" :class="classList"><img :src="activeIcon" v-if="icon"> <slot>Click Here</slot></button>
  917. `
  918. })
  919. /**
  920. * A icon Vue Component
  921. */
  922. app.component('icon', {
  923. delimiters: ['[[', ']]'],
  924. props: {
  925. icon: {
  926. type: String,
  927. required: true,
  928. default: '/assets/tabler_icons/circle-dotted.svg'
  929. }
  930. },
  931. template: `
  932. <span class="icon"><img :src="icon"></span>
  933. `
  934. })
  935. /**
  936. * Mounts the app to the DOM element with the id 'app'
  937. */
  938. vm = app.mount('#app')
  939. /**
  940. * Legacy functions for displaying old rules
  941. */
  942. // Turns RuleBuilder contents into an output-ready nested array
  943. // Returns empty array if no modules
  944. function builderArray() {
  945. var modules = document.getElementById("module-input").children;
  946. // takes an array of children
  947. // returns an array with all modules in the array, recursively nested
  948. function iterateArray(childs) {
  949. var moduleArray = [];
  950. if (childs.length > 0) {
  951. for (var i = 0; i < childs.length; i++) {
  952. module = childs[i];
  953. if (module.classList[0] == "module") {
  954. var moduleName = module.children.item("module-name");
  955. var moduleData = moduleName.title;
  956. var moduleChilds = module.children;
  957. moduleArray.push(
  958. [stripHTML(moduleName.innerHTML),
  959. stripHTML(moduleData),
  960. iterateArray(moduleChilds)]);
  961. }
  962. }
  963. }
  964. return moduleArray;
  965. } // end function
  966. return iterateArray(modules);
  967. }
  968. // returns HTML version of Builder content
  969. function displayBuilderHTML() {
  970. var output = "";
  971. var mainArray = builderArray();
  972. function arrayHTML(thisArray) {
  973. var thisOutput = "";
  974. if (thisArray.length > 0) {
  975. thisOutput += '<ul>\n';
  976. for (var i = 0; i < thisArray.length; i++) {
  977. var item = thisArray[i];
  978. thisOutput += '<li><strong>' + item[0] + '</strong> ';
  979. thisOutput += item[1] + '</li>\n';
  980. if (item[2].length > 0) {
  981. thisOutput += arrayHTML(item[2]);
  982. }
  983. }
  984. thisOutput += '</ul>\n';
  985. }
  986. return thisOutput
  987. }
  988. if (mainArray.length > 0) {
  989. output += '<div class="builder-list">\n';
  990. output += arrayHTML(mainArray) + '\n</div>\n';
  991. }
  992. document.getElementById("builder-field").innerHTML = output;
  993. }
  994. // Removes all HTML content, replacing line break tags with newlines
  995. function stripHTML(input) {
  996. input = input.replace(/<br ?\/?>/ig, "\n").replace(/(<([^>]+)>)/ig, '');
  997. return input;
  998. }