vue.rules.js 33 KB

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