vue.rules.js 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088
  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>: [[module.summary]]
  907. <span class="module__config">
  908. <span v-for="(value, key) in module.config">
  909. <br />[[key]]: [[value]]
  910. </span>
  911. </span>
  912. <ul class="submodules" v-if="module.modules && module.modules.length">
  913. <module-list v-for="submodule in module.modules" :module="submodule" :hide-icon="hideIcon"></module-list>
  914. </ul>
  915. </li>
  916. `
  917. })
  918. /**
  919. * A simple button Vue Component
  920. */
  921. app.component('vueButton', {
  922. delimiters: ['[[', ']]'],
  923. props: {
  924. icon: {
  925. type: String,
  926. required: false,
  927. default: false
  928. },
  929. loading: {
  930. type: Boolean,
  931. required: false,
  932. default: false
  933. }
  934. },
  935. computed: {
  936. classList() {
  937. return {
  938. 'has-icon': this.icon,
  939. 'is-loading': this.loading
  940. };
  941. },
  942. activeIcon() {
  943. return this.loading ? '/assets/tabler_icons/refresh.svg' : this.icon;
  944. }
  945. },
  946. template: `
  947. <button class="btn" :class="classList"><img :src="activeIcon" v-if="icon"> <slot>Click Here</slot></button>
  948. `
  949. })
  950. /**
  951. * A icon Vue Component
  952. */
  953. app.component('icon', {
  954. delimiters: ['[[', ']]'],
  955. props: {
  956. icon: {
  957. type: String,
  958. required: true,
  959. default: '/assets/tabler_icons/circle-dotted.svg'
  960. }
  961. },
  962. template: `
  963. <span class="icon"><img :src="icon"></span>
  964. `
  965. })
  966. /**
  967. * Mounts the app to the DOM element with the id 'app'
  968. */
  969. vm = app.mount('#app')
  970. /**
  971. * Legacy functions for displaying old rules
  972. */
  973. // Turns RuleBuilder contents into an output-ready nested array
  974. // Returns empty array if no modules
  975. function builderArray() {
  976. var modules = document.getElementById("module-input").children;
  977. // takes an array of children
  978. // returns an array with all modules in the array, recursively nested
  979. function iterateArray(childs) {
  980. var moduleArray = [];
  981. if (childs.length > 0) {
  982. for (var i = 0; i < childs.length; i++) {
  983. module = childs[i];
  984. if (module.classList[0] == "module") {
  985. var moduleName = module.children.item("module-name");
  986. var moduleData = moduleName.title;
  987. var moduleChilds = module.children;
  988. moduleArray.push(
  989. [stripHTML(moduleName.innerHTML),
  990. stripHTML(moduleData),
  991. iterateArray(moduleChilds)]);
  992. }
  993. }
  994. }
  995. return moduleArray;
  996. } // end function
  997. return iterateArray(modules);
  998. }
  999. // returns HTML version of Builder content
  1000. function displayBuilderHTML() {
  1001. var output = "";
  1002. var mainArray = builderArray();
  1003. function arrayHTML(thisArray) {
  1004. var thisOutput = "";
  1005. if (thisArray.length > 0) {
  1006. thisOutput += '<ul>\n';
  1007. for (var i = 0; i < thisArray.length; i++) {
  1008. var item = thisArray[i];
  1009. thisOutput += '<li><strong>' + item[0] + '</strong> ';
  1010. thisOutput += item[1] + '</li>\n';
  1011. if (item[2].length > 0) {
  1012. thisOutput += arrayHTML(item[2]);
  1013. }
  1014. }
  1015. thisOutput += '</ul>\n';
  1016. }
  1017. return thisOutput
  1018. }
  1019. if (mainArray.length > 0) {
  1020. output += '<div class="builder-list">\n';
  1021. output += arrayHTML(mainArray) + '\n</div>\n';
  1022. }
  1023. document.getElementById("builder-field").innerHTML = output;
  1024. }
  1025. // Removes all HTML content, replacing line break tags with newlines
  1026. function stripHTML(input) {
  1027. input = input.replace(/<br ?\/?>/ig, "\n").replace(/(<([^>]+)>)/ig, '');
  1028. return input;
  1029. }