vue.rules.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059
  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 { ...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. // delete unnecessary properties
  265. delete output.content;
  266. delete output.readonly;
  267. // TODO: give module a unique id
  268. // if (output.moduleID) output.moduleID = this.getUniqueId(output.moduleID);
  269. return output;
  270. },
  271. /**
  272. * Handles the click event to copy a module
  273. * @param {Event} ev the click event
  274. */
  275. handleClickCopyModule(ev) {
  276. const clickTarget = this.getClosestModule(ev.target);
  277. if (!clickTarget) return;
  278. this.copyModule(clickTarget.module);
  279. },
  280. /**
  281. * Handles the click event to edit a module
  282. * @param {Event} ev the click event
  283. */
  284. handleClickEditModule(ev) {
  285. const clickTarget = this.getClosestModule(ev.target);
  286. if (!clickTarget) return;
  287. this.editModule(clickTarget.module);
  288. },
  289. /**
  290. * Copies a module to the editor
  291. * @param {Object} module the module to copy
  292. */
  293. copyModule(module) {
  294. this.copyToEditor(module);
  295. },
  296. /**
  297. * moves a module to the editor
  298. * @param {Object} module the module to edit
  299. */
  300. editModule(module) {
  301. this.addToEditor(module);
  302. },
  303. /**
  304. * add a module to another module (or to the rule by default) as a submodule
  305. * @param {Object} module to add
  306. * @param {Object} target a module or the rule Object where the module should be added as a submodule
  307. */
  308. addModule(module,target = this.rule) {
  309. target.modules.push(module);
  310. },
  311. /**
  312. * remove a module from another module (or from the rule)
  313. * recursively moves through all submodules in the target
  314. * removes ONLY the first instance of the module
  315. * @param {Object} module the module to remove from target
  316. * @param {Object} target the module or rule to remove the module from (defaults to rule)
  317. */
  318. removeModule(module, target = this.rule) {
  319. if (! this.moduleContains(module, target)) return; // if the module is not in the target, do nothing
  320. //
  321. target.modules.forEach((m, idx) => {
  322. if (m === module) {
  323. target.modules.splice(idx, 1);
  324. return;
  325. } else {
  326. this.removeModule(module, m);
  327. }
  328. });
  329. },
  330. /**
  331. * Deletes custom module from the customModules array and clears the editor
  332. * @param {Object} module the module to be deleted
  333. */
  334. deleteModule(module) {
  335. this.removeCustomModule(module);
  336. // TODO: only clear the editor if the module is present in the editor
  337. this.clearEditor();
  338. },
  339. /**
  340. * Handles the start drag event for a module
  341. * @param {Event} ev the drag event
  342. */
  343. startDragModule(ev) {
  344. const targetModule = this.getClosestModule(ev.target);
  345. if (!targetModule) return;
  346. const module = targetModule.module;
  347. ev.dataTransfer.setDragImage(targetModule, ev.offsetX, ev.offsetY);
  348. this.holding = {module};
  349. },
  350. /**
  351. * Handles the start drag event for a module
  352. * when the module is being rearranged within the rule
  353. * @param {Event} ev the drag event
  354. */
  355. rearrangeModule(ev) {
  356. const targetModule = this.getClosestModule(ev.target);
  357. if (!targetModule) return;
  358. const source = this.getClosestModule(targetModule.parentNode).module;
  359. const module = targetModule.module;
  360. ev.dataTransfer.setDragImage(targetModule, ev.offsetX, ev.offsetY);
  361. this.holding = {
  362. module,
  363. source,
  364. };
  365. },
  366. /**
  367. * Handles the dragend event for a module
  368. */
  369. endDragModule() {
  370. this.holding = false;
  371. },
  372. /**
  373. * Recursively searches modules and their submodules for a module
  374. * @param {Object} needle the module to search for
  375. * @param {Object} haystack the module to search in (defaults to rule)
  376. * @returns {Boolean} true if the module is in the haystack
  377. */
  378. // TODO: return the module location in the haystack (Maybe?)
  379. moduleContains(needle, haystack = this.rule) {
  380. if (! haystack.modules ) return false; // does the haystack even have modules?
  381. if (haystack.modules.includes(needle)) return true; // is the needle in the haystack?
  382. return haystack.modules.some(submodule => this.moduleContains(needle, submodule)); // is the needle in any of the submodules?
  383. },
  384. // rule methods ===========================================================
  385. /**
  386. * Handles the drop event for a module
  387. * adds the module to the closest submodule or the rule depending on what it is dropped onto
  388. * then adds the module to the editor
  389. * @param {Event} ev the drop event
  390. */
  391. dropOnRule(ev) {
  392. //TODO browser drag objects that hover over drop zone are showing a 'add' icon
  393. const landingNode = this.getClosestModule(ev.target);
  394. if (!this.holding.module || !landingNode) return; // if there is no module to drop or no landing node, do nothing
  395. const landingModule = landingNode.module; // module is set with the v-bind prop binding
  396. const holdingModule = this.holding.module;
  397. if (holdingModule === landingModule) return; // if the module is the same, do nothing
  398. // if the module being dropped is readyonly clone it, otherwise use the original
  399. const readonly = holdingModule.readonly;
  400. const module = (readonly) ? this.cloneModule(holdingModule) : holdingModule;
  401. if (this.holding.source) {
  402. // if the module has a source, remove it from that source
  403. this.removeModule(holdingModule, this.holding.source);
  404. }
  405. this.addModule(module, landingModule);
  406. this.editModule(module);
  407. this.endDragModule();
  408. },
  409. fetchRule(id) {
  410. this.loading = true;
  411. // handle legacy links
  412. // TODO: handle this at a global level
  413. let redirect = {
  414. 'benevolent_dictator': 'benevolent-dictator',
  415. circles: 'circles',
  416. consensus: 'consensus',
  417. 'do-ocracy': 'do-ocracy',
  418. 'elected_board': 'elected-board',
  419. jury: 'jury',
  420. petition: 'petition',
  421. 'self-appointed_board': 'self-appointed-board',
  422. }
  423. // if the rule is a legacy link, redirect
  424. if (redirect[id]) {
  425. location.href = `/templates/${redirect[id]}`;
  426. return;
  427. }
  428. const store = new SteinStore(
  429. this.steinAPI
  430. );
  431. (async () => {
  432. var rule = [];
  433. // read values from all sheets
  434. await store.read('rules', { search: { ruleID: id } }).then(data => {
  435. // test if there's anything in data
  436. if (data.length > 0) {
  437. rule = data[0];
  438. }
  439. console.log(rule);
  440. });
  441. // no rule found, exit
  442. // TODO: inform the user that the rule was not found
  443. if (!rule) {
  444. this.loading = false;
  445. return;
  446. }
  447. // if this is a legacy (pre-v3) set it as such
  448. if (rule.version < 3) {
  449. this.loading = false;
  450. this.legacy = true;
  451. this.rule = rule;
  452. Vue.nextTick(() => {
  453. if (rule.version == 2) displayBuilderHTML();
  454. });
  455. return;
  456. }
  457. this.rule = {
  458. ruleID: rule.ruleID,
  459. timestamp: rule.timestamp,
  460. icon: rule.icon,
  461. name: rule.name,
  462. lineage: rule.lineage,
  463. summary: rule.summary,
  464. config: rule.config,
  465. creator: {
  466. name: rule.creatorName,
  467. url: rule.creatorUrl,
  468. },
  469. modules: (rule.modules) ? JSON.parse(rule.modules) : []
  470. }
  471. /** Add name to <title> for v3+ rules */
  472. document.title = rule.name + " / CommunityRule"
  473. this.loading = false;
  474. })();
  475. },
  476. // editor methods =========================================================
  477. /**
  478. * Adds a module to the editor
  479. * @param {Object} module the module to add to the editor
  480. */
  481. addToEditor(module) {
  482. this.preventEditorLoss();
  483. this.setEditorSource(module);
  484. this.setEditorPreviousState(module);
  485. this.editor.module = module;
  486. },
  487. /**
  488. * Copies a module to the editor
  489. * @param {Object} module the module to copy to the editor
  490. */
  491. copyToEditor(module) {
  492. const moduleCopy = this.cloneModule(module);
  493. this.preventEditorLoss();
  494. this.setEditorSource(module);
  495. this.setEditorPreviousState(moduleCopy);
  496. this.editor.module = moduleCopy;
  497. },
  498. /**
  499. * Takes a module and clones it into the editor.previousState
  500. * @param {Object} module the module to add to the previous state
  501. */
  502. setEditorPreviousState(module) {
  503. this.editor.previousState = { ...module };
  504. },
  505. /**
  506. * Sets the editor.source to the module
  507. * @param {Object} module the module to set the editor source to
  508. */
  509. setEditorSource(module) {
  510. this.editor.source = module;
  511. },
  512. /**
  513. * Checks if the editor has edits and that the current module in the editor is not present in the rule
  514. * If the module in the editor would be lost, confirm with the user
  515. * then adds the module to the customModules array
  516. */
  517. preventEditorLoss() {
  518. // if the editor has changes and the module isn't in the rule, save it to the custom modules
  519. if (this.editorHasEdits && !this.moduleContains(this.editor.module)) {
  520. this.confirm('You have unsaved changes. Are you sure you want to discard them?')
  521. this.addCustomModule(this.editor.module);
  522. }
  523. },
  524. /**
  525. * Handles the click event for adding a module from the editor to the rule
  526. */
  527. clickAddModule() {
  528. const module = this.editor.module;
  529. this.addModule(module);
  530. this.addToEditor(module);
  531. },
  532. /**
  533. * Handles the click event for removing a module in the editor from the rule
  534. */
  535. clickRemoveModule() {
  536. const module = this.editor.module;
  537. this.removeModule(module);
  538. },
  539. /**
  540. * Clears the editor
  541. */
  542. clearEditor() {
  543. this.preventEditorLoss();
  544. this.editor.module = null;
  545. this.editor.previousState = null;
  546. },
  547. /**
  548. * Saves the module in the editor to customModules array
  549. */
  550. saveEditor() {
  551. this.addCustomModule(this.editor.module);
  552. this.setEditorPreviousState(this.editor.module);
  553. },
  554. // custom module methods ==================================================
  555. /**
  556. * Adds a module to the customModules array
  557. * @param {Object} module the module to add to the customModules array
  558. */
  559. addCustomModule(module) {
  560. // if module is not in customModules, add it
  561. if (!this.customModules.includes(module)) {
  562. this.customModules.unshift(module);
  563. }
  564. },
  565. /**
  566. * Creates a new module, set's a default name, and adds it to the editor
  567. */
  568. newCustomModule() {
  569. const module = this.newModule();
  570. module.name = 'New Module';
  571. this.addToEditor(module);
  572. },
  573. /**
  574. * Removes a module from the customModules array
  575. * @param {Object} module the module to remove from the customModules array
  576. */
  577. removeCustomModule(module) {
  578. this.confirm("are you sure you want to remove this custom module?");
  579. const index = this.customModules.indexOf(module);
  580. this.customModules.splice(index, 1);
  581. },
  582. /**
  583. * Handles confirmation messages for users
  584. * @param {String} msg the message to display in the confirm dialog
  585. */
  586. // TODO: add a confirm dialog and return boolean based on user input
  587. confirm(msg) {
  588. console.log(msg);
  589. },
  590. // export and download methods =============================================
  591. /**
  592. * Handles click event for publishing the rule
  593. */
  594. handleClickPublish() {
  595. // Confirm user knows what they're getting into
  596. if (!confirm("Publish to the public Library?")) return;
  597. if ( !this.rule.name ) {
  598. alert("Please enter a name for this rule.");
  599. return;
  600. }
  601. if ( this.rule.modules.length < 1 ) {
  602. alert("Please add at least one module to this rule.");
  603. return;
  604. }
  605. this.publishing = true;
  606. const rule = this.ruleExport;
  607. const ruleID = new Date().getTime(); // TODO: allow for custom named IDs, check for uniqueness
  608. // add to database
  609. const store = new SteinStore(
  610. this.steinAPI
  611. );
  612. store.append('rules', [{
  613. ruleID: ruleID,
  614. timestamp: rule.timestamp,
  615. icon: rule.icon,
  616. name: rule.name,
  617. lineage: rule.lineage,
  618. summary: rule.summary,
  619. config: this.jsonify(rule.config),
  620. modules: this.jsonify(rule.modules),
  621. creatorName: rule.creator.name,
  622. creatorUrl: rule.creator.url,
  623. version: 3
  624. }]).then(data => {
  625. this.publishing = false;
  626. window.open("/create/?r=" + ruleID, "_self", false);
  627. });
  628. },
  629. /**
  630. * Handles the click event for downloading the rule as a Markdown file
  631. * Creates a YAML string of the rule
  632. * Then adds it to the bottom of a markdown file
  633. * created from the #rule-export html element
  634. */
  635. handleClickDownload() {
  636. const yaml = jsyaml.dump(this.ruleExport);
  637. const turndown = new TurndownService();
  638. const html = document.getElementById('rule-export');
  639. if (!html) return;
  640. const markdown = turndown.turndown(html);
  641. const output = markdown + '\n\n----\n```yaml\n' + yaml + '\n```';
  642. this.saveFile(`${this.ruleExport.ruleID}.md`, output, 'text/markdown');
  643. },
  644. /**
  645. * Handles the click event for downloading the rule as a JSON file
  646. */
  647. handleClickExport() {
  648. const output = this.json;
  649. this.saveFile(`${this.ruleExport.ruleID}.json`, output, 'application/json');
  650. },
  651. /**
  652. * IE10+ Firefox, and Chrome method for saving a file
  653. * https://stackoverflow.com/a/33542499
  654. * @param {String} filename name of the file to save
  655. * @param {String} data data to save into a file
  656. * @param {String} type MIME type of the file
  657. */
  658. saveFile(filename, data, type) {
  659. const blob = new Blob([data], { type: type });
  660. if (window.navigator.msSaveOrOpenBlob) {
  661. window.navigator.msSaveBlob(blob, filename);
  662. }
  663. else {
  664. const elem = window.document.createElement('a');
  665. elem.href = window.URL.createObjectURL(blob);
  666. elem.download = filename;
  667. document.body.appendChild(elem);
  668. elem.click();
  669. document.body.removeChild(elem);
  670. }
  671. },
  672. /**
  673. * Handles the click event for importing a rule from a JSON file
  674. */
  675. handleClickImport() {
  676. },
  677. // utility methods ===========================================================
  678. /**
  679. * Takes an html element and finds the closest node (inclusive) that has a data-module-id attribute
  680. * @param {Node} el the html element to check
  681. * @returns {Node} the closest node with a data-module-id attribute
  682. */
  683. getClosestModule(el) {
  684. const parent = el.closest('[data-module-id]');
  685. if (!parent) return false;
  686. if (!parent.module) return false;
  687. return parent;
  688. },
  689. /**
  690. * Handles the click event for activating the rule preview
  691. */
  692. clickPreview() {
  693. if(this.template) this.rule.icon = ''; // TODO: find a less hacky way to reset template icons
  694. this.view = false;
  695. this.preview = !this.preview;
  696. },
  697. /**
  698. * Filters module library based on the search term
  699. * @param {String} type the name of the type to filter
  700. * @returns {Array} the filtered module library
  701. */
  702. getModulesByType(type) {
  703. return this.modules.filter(module => module.type === type)
  704. },
  705. /**
  706. * Slugifies a string
  707. * https://gist.github.com/codeguy/6684588 (one of the comments)
  708. * @param {String} string the string to slugify
  709. * @returns
  710. */
  711. slugify(string) {
  712. const separator = '-';
  713. return string
  714. .toString()
  715. .normalize('NFD') // split an accented letter in the base letter and the accent
  716. .replace(/[\u0300-\u036f]/g, '') // remove all previously split accents
  717. .toLowerCase()
  718. .replace(/[^a-z0-9 -]/g, '') // remove all chars not letters, numbers and spaces (to be replaced)
  719. .trim()
  720. .replace(/\s+/g, separator);
  721. },
  722. /**
  723. * Creates a human readable timestamp string
  724. * @param {String} date optional date to format
  725. * @returns {String} human readable date '2022.4.12 14:44:56 UTC'
  726. */
  727. timesString(date) {
  728. let now = new Date(date);
  729. if (isNaN(now)) now = new Date();
  730. return now.getUTCFullYear() + '.' + (now.getUTCMonth() + 1) + '.' + now.getUTCDate()
  731. + ' ' + now.getUTCHours() + ":" + now.getUTCMinutes() + ":" + now.getUTCSeconds()
  732. + ' UTC';
  733. },
  734. /**
  735. * stringify an Object
  736. * @param {Object} obj
  737. * @returns JSON string
  738. */
  739. jsonify(obj) {
  740. return JSON.stringify(obj, null, 2);
  741. },
  742. /**
  743. * Takes a moduleID and checks if that moduleID is in use
  744. * if so, returns the moduleID with a number appended to it
  745. * @param {String} test the moduleID to test
  746. * @returns {String} the moduleID, or if in use, with a number appended to it
  747. */
  748. getUniqueId(test) {
  749. let id = test;
  750. let i = 0;
  751. while (this.listModuleIds.includes(id)) {
  752. i++;
  753. id = `${test}-${i}`;
  754. }
  755. return id
  756. },
  757. },
  758. });
  759. /**
  760. * The Module Vue Component
  761. */
  762. app.component('module', {
  763. delimiters: ['[[', ']]'],
  764. inject: ['editor'],
  765. props: {
  766. module: {
  767. type: Object,
  768. required: true,
  769. },
  770. inEditor: {
  771. type: Boolean,
  772. default: false,
  773. },
  774. hideSubmodules: {
  775. type: Boolean,
  776. default: false,
  777. }
  778. },
  779. data() {
  780. return {
  781. defaultIcon: '/assets/tabler_icons/circle-dotted.svg',
  782. mouseOver: false,
  783. dragOver: false
  784. }
  785. },
  786. computed: {
  787. icon() {
  788. return this.module.icon ? this.module.icon : this.defaultIcon;
  789. },
  790. moduleClass() {
  791. return {
  792. 'in-editor': this.editor.source == this.module,
  793. 'mouse-over': this.mouseOver,
  794. // TODO: when dragging over the icon the drag-over class disappears
  795. 'drag-over': this.dragOver
  796. }
  797. }
  798. },
  799. template: `
  800. <div
  801. class="module"
  802. :class="moduleClass"
  803. .module="module"
  804. @mouseover.stop="this.mouseOver = true"
  805. @mouseout="this.mouseOver = false"
  806. @dragenter.self="this.dragOver = true"
  807. @dragleave.self="this.dragOver = false"
  808. @drop.self="this.dragOver = false"
  809. :data-module-id="module.moduleID"
  810. >
  811. <div class="module__icon-wrapper">
  812. <span class="module__grain"><img src="/assets/tabler_icons/grain.svg"></span>
  813. <span class="module__icon"><img :src="icon"></span>
  814. </div>
  815. [[module.name]]
  816. <div class="submodules" v-if="!hideSubmodules && module.modules && module.modules.length">
  817. <module v-for="submodule in module.modules" :module="submodule" draggable="true"></module>
  818. </div>
  819. </div>
  820. `
  821. })
  822. /**
  823. * A non-interactive Module Vue Component
  824. * Used for displaying the module
  825. */
  826. app.component('moduleDisplay', {
  827. delimiters: ['[[', ']]'],
  828. props: {
  829. module: {
  830. type: Object,
  831. required: true,
  832. }
  833. },
  834. data() {
  835. return {
  836. defaultIcon: '/assets/tabler_icons/circle-dotted.svg'
  837. }
  838. },
  839. computed: {
  840. icon() {
  841. return this.module.icon ? this.module.icon : this.defaultIcon;
  842. }
  843. },
  844. template: `
  845. <div
  846. class="module"
  847. .module="module"
  848. >
  849. <div class="module__icon-wrapper">
  850. <span class="module__icon"><img :src="icon"></span>
  851. </div>
  852. [[module.name]]
  853. <div class="submodules" v-if="module.modules && module.modules.length">
  854. <module-display v-for="submodule in module.modules" :module="submodule"></module-display>
  855. </div>
  856. </div>
  857. `
  858. })
  859. /**
  860. * The Module list Vue Component
  861. */
  862. app.component('moduleList', {
  863. delimiters: ['[[', ']]'],
  864. props: {
  865. module: {
  866. type: Object,
  867. required: true,
  868. },
  869. hideIcon: {
  870. type: Boolean,
  871. default: false,
  872. }
  873. },
  874. data() {
  875. return {
  876. defaultIcon: '/assets/tabler_icons/circle-dotted.svg'
  877. }
  878. },
  879. computed: {
  880. icon() {
  881. return this.module.icon ? this.module.icon : this.defaultIcon;
  882. }
  883. },
  884. template: `
  885. <li class="module-list-item">
  886. <span class="module__icon" v-if="!hideIcon"><img :src="icon"> </span><strong>[[module.name]]</strong>: [[module.summary]]
  887. <ul class="submodules" v-if="module.modules && module.modules.length">
  888. <module-list v-for="submodule in module.modules" :module="submodule" :hide-icon="hideIcon"></module-list>
  889. </ul>
  890. </li>
  891. `
  892. })
  893. /**
  894. * A simple button Vue Component
  895. */
  896. app.component('vueButton', {
  897. delimiters: ['[[', ']]'],
  898. props: {
  899. icon: {
  900. type: String,
  901. required: false,
  902. default: false
  903. },
  904. loading: {
  905. type: Boolean,
  906. required: false,
  907. default: false
  908. }
  909. },
  910. computed: {
  911. classList() {
  912. return {
  913. 'has-icon': this.icon,
  914. 'is-loading': this.loading
  915. };
  916. },
  917. activeIcon() {
  918. return this.loading ? '/assets/tabler_icons/refresh.svg' : this.icon;
  919. }
  920. },
  921. template: `
  922. <button class="btn" :class="classList"><img :src="activeIcon" v-if="icon"> <slot>Click Here</slot></button>
  923. `
  924. })
  925. /**
  926. * A icon Vue Component
  927. */
  928. app.component('icon', {
  929. delimiters: ['[[', ']]'],
  930. props: {
  931. icon: {
  932. type: String,
  933. required: true,
  934. default: '/assets/tabler_icons/circle-dotted.svg'
  935. }
  936. },
  937. template: `
  938. <span class="icon"><img :src="icon"></span>
  939. `
  940. })
  941. /**
  942. * Mounts the app to the DOM element with the id 'app'
  943. */
  944. vm = app.mount('#app')
  945. /**
  946. * Legacy functions for displaying old rules
  947. */
  948. // Turns RuleBuilder contents into an output-ready nested array
  949. // Returns empty array if no modules
  950. function builderArray() {
  951. var modules = document.getElementById("module-input").children;
  952. // takes an array of children
  953. // returns an array with all modules in the array, recursively nested
  954. function iterateArray(childs) {
  955. var moduleArray = [];
  956. if (childs.length > 0) {
  957. for (var i = 0; i < childs.length; i++) {
  958. module = childs[i];
  959. if (module.classList[0] == "module") {
  960. var moduleName = module.children.item("module-name");
  961. var moduleData = moduleName.title;
  962. var moduleChilds = module.children;
  963. moduleArray.push(
  964. [stripHTML(moduleName.innerHTML),
  965. stripHTML(moduleData),
  966. iterateArray(moduleChilds)]);
  967. }
  968. }
  969. }
  970. return moduleArray;
  971. } // end function
  972. return iterateArray(modules);
  973. }
  974. // returns HTML version of Builder content
  975. function displayBuilderHTML() {
  976. var output = "";
  977. var mainArray = builderArray();
  978. function arrayHTML(thisArray) {
  979. var thisOutput = "";
  980. if (thisArray.length > 0) {
  981. thisOutput += '<ul>\n';
  982. for (var i = 0; i < thisArray.length; i++) {
  983. var item = thisArray[i];
  984. thisOutput += '<li><strong>' + item[0] + '</strong> ';
  985. thisOutput += item[1] + '</li>\n';
  986. if (item[2].length > 0) {
  987. thisOutput += arrayHTML(item[2]);
  988. }
  989. }
  990. thisOutput += '</ul>\n';
  991. }
  992. return thisOutput
  993. }
  994. if (mainArray.length > 0) {
  995. output += '<div class="builder-list">\n';
  996. output += arrayHTML(mainArray) + '\n</div>\n';
  997. }
  998. document.getElementById("builder-field").innerHTML = output;
  999. }
  1000. // Removes all HTML content, replacing line break tags with newlines
  1001. function stripHTML(input) {
  1002. input = input.replace(/<br ?\/?>/ig, "\n").replace(/(<([^>]+)>)/ig, '');
  1003. return input;
  1004. }