vue.rules.js 33 KB

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