rule-scripts.html 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. <!-- Enables dragging on mobile
  2. https://github.com/Bernardo-Castilho/dragdroptouch -->
  3. <script src="/assets/DragDropTouch.js"></script>
  4. <script>
  5. // Enter JavaScript-land!
  6. // First, some functions, followed by initialization commands
  7. // Begin BUILDER functions
  8. // source: https://www.codecanal.com/html5-drag-and-copy/
  9. function allowDrop(ev) {
  10. ev.preventDefault();
  11. }
  12. function drag(ev) {
  13. ev.dataTransfer.setData("text", ev.target.id);
  14. }
  15. function drop(ev) {
  16. ev.preventDefault();
  17. var target = ev.target;
  18. // First, confirm target location is valid
  19. function targetCheck () {
  20. if (!editMode) {
  21. return false;
  22. } else if (target.id == "module-input") {
  23. return true;
  24. } else if (!document.getElementById("module-input").contains(target)) {
  25. // Ignore destinations not in the correct area
  26. return false;
  27. } else if (target.id == "drag-directions") {
  28. // Prevents dropping into dummy text field
  29. target = target.parentElement;
  30. return true;
  31. } else if (target.classList[0] == "module") {
  32. return true;
  33. } else {
  34. // be sure we're adding to module, not its children
  35. target = target.parentElement;
  36. return targetCheck();
  37. }
  38. }
  39. if (!targetCheck()) { return; }
  40. // Set up transfer
  41. var data = ev.dataTransfer.getData("text");
  42. // Iff module is from the menu clone it
  43. var module = document.getElementById(data);
  44. if ((module.parentElement.id == "module-menu") ||
  45. (module.parentElement.parentElement.id == "module-menu")) {
  46. // ^ because a subgroup might be parent
  47. module = module.cloneNode(true);
  48. var name = null;
  49. if (module.id == "module-custom") {
  50. // For custom modules: replace the <input> with text
  51. name = module.getElementsByTagName("input")[0].value;
  52. module.getElementsByTagName("input")[0].remove();
  53. var customText = document.createElement("span");
  54. customText.id = "module-name";
  55. customText.append(name);
  56. module.prepend(customText);
  57. }
  58. // append id with unique timestamp
  59. var nowModule = new Date();
  60. module.id += "-" + nowModule.getTime();
  61. }
  62. // hide the info button
  63. module.children[1].style.display = "none";
  64. // display the deletion button
  65. module.children[2].style.display = "inline";
  66. // pop it in!
  67. target.appendChild(module);
  68. // add module-field button (using HTML so it saves to Library)
  69. module.outerHTML = module.outerHTML.replace("id=\"module-name\"",
  70. "id=\"module-name\" onclick=\"moduleEditField(this.parentNode.id)\"");
  71. // create the module-field
  72. moduleEditField(module.id);
  73. // be sure the dummy text is gone
  74. if (document.contains(document.getElementById("drag-directions"))) {
  75. document.getElementById("drag-directions").remove();
  76. }
  77. }
  78. // Edits the title field of a given module based on #custom-field
  79. function moduleTitleEdit(moduleID) {
  80. var module = document.getElementById(moduleID).children[0];
  81. var content =
  82. stripHTML(document.getElementById("custom-field").innerHTML);
  83. module.title = content;
  84. }
  85. // Sets up a field for displaying and editing module details
  86. function moduleEditField(moduleID) {
  87. var module = document.getElementById(moduleID);
  88. var moduleName = module.children[0].innerHTML;
  89. var moduleTitle = module.children[0].title;
  90. if (editMode) {
  91. var query = "How does the <strong>" + moduleName
  92. + "</strong> module work?";
  93. var destination = document.getElementById("builder-field");
  94. if (moduleName == null) { moduleName = ""; }
  95. var output = '\n<div id="custom-field-container">';
  96. output += '<span class="prompt">' + query + '</span>';
  97. output += '<div class="field-controls"><a onclick="this.parentNode.parentNode.remove()"><img src="{% link assets/tabler_icons/x.svg %}" class="delete-module" /></a></div>';
  98. output += '<p contenteditable="true" class="editable" id="custom-field" oninput="moduleTitleEdit(\'' + moduleID + '\')">' + moduleTitle + '</p>';
  99. output += '</div>\n';
  100. destination.innerHTML = output;
  101. } else {
  102. var output = '\n<div id="custom-field-container">';
  103. output += '<div class="field-controls"><a onclick="this.parentNode.parentNode.remove()"><img src="{% link assets/tabler_icons/x.svg %}" class="delete-module" /></a></div>';
  104. output += '<p class="editable" id="custom-field">'
  105. + moduleTitle + '</p>';
  106. }
  107. }
  108. // Tests if the RuleBuilder is empty
  109. function builderEmpty() {
  110. var builder = document.getElementById("module-input");
  111. var childs = builder.children;
  112. if (builder.getElementsByClassName("module").length > 0) {
  113. return false;
  114. } else {
  115. return true;
  116. }
  117. }
  118. // Turns RuleBuilder contents into an output-ready nested array
  119. // Returns empty array if no modules
  120. function builderArray() {
  121. var modules = document.getElementById("module-input").children;
  122. // takes an array of children
  123. // returns an array with all modules in the array, recursively nested
  124. function iterateArray (childs) {
  125. var moduleArray = [];
  126. if (childs.length > 0) {
  127. for (var i = 0; i < childs.length; i++) {
  128. module = childs[i];
  129. if (module.classList[0] == "module") {
  130. var moduleName = module.children.item("module-name");
  131. var moduleData = moduleName.title;
  132. var moduleChilds = module.children;
  133. moduleArray.push(
  134. [stripHTML(moduleName.innerHTML),
  135. stripHTML(moduleData),
  136. iterateArray(moduleChilds)]);
  137. }
  138. }
  139. }
  140. return moduleArray;
  141. } // end function
  142. return iterateArray(modules);
  143. }
  144. // returns HTML version of Builder content
  145. function displayBuilderHTML() {
  146. var output = "";
  147. var mainArray = builderArray();
  148. function arrayHTML(thisArray) {
  149. var thisOutput = "";
  150. if (thisArray.length > 0) {
  151. thisOutput += '<ul>\n';
  152. for (var i = 0; i < thisArray.length; i++) {
  153. var item = thisArray[i];
  154. thisOutput += '<li><strong>' + item[0] + '</strong> ';
  155. thisOutput += item[1] + '</li>\n';
  156. if (item[2].length > 0) {
  157. thisOutput += arrayHTML(item[2]);
  158. }
  159. }
  160. thisOutput += '</ul>\n';
  161. }
  162. return thisOutput
  163. }
  164. if (mainArray.length > 0) {
  165. output += '<div class="builder-list">\n';
  166. output += arrayHTML(mainArray) + '\n</div>\n';
  167. }
  168. return output;
  169. }
  170. // returns Markdown version of Builder content
  171. function displayBuilderMD() {
  172. var mainArray = builderArray();
  173. var indentLevel = 0;
  174. function arrayMD(thisArray) {
  175. var thisOutput = "";
  176. if (thisArray.length > 0) {
  177. for (var i = 0; i < thisArray.length; i++) {
  178. var item = thisArray[i];
  179. for (var x = 0; x < indentLevel; x++) {
  180. thisOutput += " ";
  181. }
  182. thisOutput += "* **" + item[0] + "** ";
  183. thisOutput += item[1] + "\n";
  184. if (item[2].length > 0) {
  185. indentLevel++;
  186. thisOutput += arrayMD(item[2]);
  187. indentLevel--;
  188. }
  189. }
  190. }
  191. return thisOutput;
  192. }
  193. return arrayMD(mainArray);
  194. }
  195. // end RuleBuilder functions
  196. // Removes all HTML content, replacing line break tags with newlines
  197. function stripHTML(input) {
  198. input = input.replace(/<br ?\/?>/ig, "\n").replace(/(<([^>]+)>)/ig,'');
  199. return input;
  200. }
  201. // Intercepts the paste event for editable fields and
  202. // converts the pasted content to plain text,
  203. // stripping styles and unwanted markup added by programs like Word.
  204. function handleEditablePaste(event) {
  205. try {
  206. var pastedText = event.clipboardData
  207. ? event.clipboardData.getData("text/plain")
  208. : window.clipboardData.getData("Text"); // support IE
  209. var cleanedText = cleanPastedText(pastedText);
  210. // Pastes the cleaned up text.
  211. if (document.queryCommandSupported('insertText')) {
  212. document.execCommand('insertText', false, cleanedText);
  213. } else { // support IE
  214. document.execCommand('paste', false, cleanedText);
  215. }
  216. event.stopPropagation();
  217. event.preventDefault();
  218. return false;
  219. } catch (err) {
  220. // If anything goes wrong with browser compatibility,
  221. // pass the event through without modification.
  222. return true;
  223. }
  224. }
  225. // Removes junk that comes with pasting from text editors like Word.
  226. // taken from https://stackoverflow.com/questions/2875027/clean-microsoft-word-pasted-text-using-javascript
  227. function cleanPastedText(text) {
  228. return text.replace(/.*<!--.*-->/g, "");
  229. }
  230. // toggleVisible(id)
  231. // Toggles the visibility of a given element by given ID
  232. function toggleVisible(id) {
  233. var x = document.getElementById(id);
  234. if (x.style.display === "none") {
  235. x.style.display = "block";
  236. } else {
  237. x.style.display = "none";
  238. }
  239. }
  240. // classDisplayAll(className, value)
  241. // Assigns given display value to all elements with a given className
  242. function classDisplayAll(className, value) {
  243. var elements = document.getElementsByClassName(className);
  244. for (var i = 0; i < elements.length; i++) {
  245. elements[i].style.display = value;
  246. }
  247. }
  248. // toggleEditMode()
  249. // Toggles whether editable fields are editable or not
  250. // and removes editing tools.
  251. function toggleEditMode() {
  252. if (editMode === true) { // switch to preview mode
  253. editMode = false;
  254. classDisplayAll("prompt","none");
  255. classDisplayAll("delete-module","none");
  256. var editableFields = document.getElementsByClassName("editable");
  257. // de-editable-ize the editable fields
  258. for (var i = 0; i < editableFields.length; i++) {
  259. editableFields[i].contentEditable = "false";
  260. editableFields[i].style.borderStyle = "none";
  261. // Remove empty fields entirely
  262. var content = editableFields[i].innerHTML;
  263. content = stripHTML(content);
  264. if (content === "") {
  265. editableFields[i].style.display = "none";
  266. }
  267. }
  268. // RuleBuilder sections
  269. if (builderEmpty()) {
  270. document.getElementById("rule-builder").style.display = "none";
  271. } else {
  272. document.getElementById("builder-field").innerHTML = displayBuilderHTML();
  273. document.getElementById("module-input").style.border = "none";
  274. }
  275. if (document.contains(document.getElementById("custom-field-container"))) {
  276. document.getElementById("custom-field-container").remove();
  277. }
  278. document.getElementById("module-menu").style.display = "none";
  279. // Handle author link
  280. var authorName = document.getElementById("author-text").value;
  281. var authorURL = document.getElementById("author-url").value;
  282. if (authorName != "") {
  283. document.getElementById("authorship-words").style.display = "inline";
  284. if (authorURL != "") { // both author and URL present
  285. document.getElementById("authorship-result").innerHTML = "<a href='" + authorURL +"'>" + authorName + "</a>";
  286. document.getElementById("authorship-result").style.display = "inline";
  287. } else { // only authorName present
  288. document.getElementById("authorship-result").innerHTML = authorName;
  289. document.getElementById("authorship-result").style.display = "inline";
  290. }
  291. } else {
  292. document.getElementById("authorship").style.display = "none";
  293. }
  294. // Finally, change button name
  295. document.getElementById("editToggle").innerHTML = "Customize";
  296. } else { // Switch to editMode
  297. editMode = true;
  298. classDisplayAll("prompt","block");
  299. classDisplayAll("editable","block");
  300. // RuleBuilder handling
  301. classDisplayAll("delete-module","inline");
  302. document.getElementById("rule-builder").style.display = "block";
  303. document.getElementById("module-menu").style.display = "block";
  304. document.getElementById("module-input").style.border = "";
  305. document.getElementById("builder-field").innerHTML = "";
  306. // link handling
  307. classDisplayAll("link-text","inline");
  308. classDisplayAll("link-url","inline");
  309. document.getElementById("authorship-result").style.display = "none";
  310. document.getElementById("authorship-words").style.display = "none";
  311. document.getElementById("authorship").style.display = "block";
  312. // make all editable fields visible
  313. var editableFields = document.getElementsByClassName("editable");
  314. for (var i = 0; i < editableFields.length; i++) {
  315. editableFields[i].style.borderStyle = "none none dashed none";
  316. editableFields[i].contentEditable = "true";
  317. }
  318. // Change button name
  319. document.getElementById("editToggle").innerHTML = "Preview";
  320. }
  321. }
  322. // toggleDisplayMode()
  323. // toggles full displayMode, the Rule-only display for a published Rule
  324. // first, initialize variable:
  325. var displayMode = false;
  326. function toggleDisplayMode() {
  327. if (displayMode == false) {
  328. editMode = true;
  329. toggleEditMode(); // turns off editMode
  330. classDisplayAll("site-nav","none");
  331. classDisplayAll("post-header","none");
  332. classDisplayAll("site-footer","none");
  333. document.getElementById("attribution").style.display = "block";
  334. document.getElementById("fork").style.display = "inline-block";
  335. document.getElementById("discuss-button").style.display = "inline-block";
  336. document.getElementById("publishRule").style.display = "none";
  337. document.getElementById("trash").style.display = "inline-block";
  338. // Turn on RuleWriter if there's content
  339. if ("" != document.getElementById("rulewriter").innerHTML) {
  340. document.getElementById("rulewriter-box").style.display = "inline-block";
  341. }
  342. // Finish
  343. displayMode = true;
  344. } else {
  345. toggleEditMode() // turns on editMode
  346. classDisplayAll("site-nav","block");
  347. classDisplayAll("post-header","block");
  348. classDisplayAll("site-footer","block");
  349. document.getElementById("attribution").style.display = "none";
  350. document.getElementById("fork").style.display = "none";
  351. document.getElementById("discuss-button").style.display = "none";
  352. document.getElementById("publishRule").style.display = "inline-block";
  353. document.getElementById("trash").style.display = "none";
  354. displayMode = false;
  355. }
  356. if (document.getElementById("lineage-list").innerHTML != "") {
  357. document.getElementById("lineage").style.display = "block";
  358. }
  359. }
  360. // textOutput()
  361. // Produces Markdown rendition of Rule from Export button
  362. function textOutput() {
  363. var filename = 'GOVERNANCE.md';
  364. // First, add title, whether there is one or not
  365. var content = '# '+ document.getElementById('communityname').innerHTML + '\n\n';
  366. content = stripHTML(content);
  367. // Next, add structure field
  368. var structure = document.getElementById('structure').innerHTML;
  369. if (structure != "") {
  370. content += stripHTML(structure) + '\n\n';
  371. }
  372. // Add Builder content
  373. if (!builderEmpty()) {
  374. content += displayBuilderMD() + "\n\n";
  375. }
  376. // Now, begin adding Writer elements
  377. var elements = document.getElementsByClassName('output');
  378. for (var i = 2; i < elements.length; i++) { // start after structure
  379. var thisBit = elements[i].innerHTML;
  380. thisBit = stripHTML(thisBit);
  381. if (thisBit != "") {
  382. if (elements[i].classList.contains("subhead")) {
  383. // Before printing subhead, make sure it's not empty
  384. var i2 = i + 1;
  385. while ((i2 < elements.length) &&
  386. (!(elements[i2].classList.contains("subhead")))) {
  387. if (elements[i2].innerHTML != "") {
  388. // in this case, it's not empty, so print and move on
  389. content += '## ';
  390. content += thisBit + '\n\n';
  391. break;
  392. } else { i2++; }
  393. } // won't print anything if a subhead has only empty children
  394. } else {
  395. // Non-subhead elements can just go ahead and print
  396. content += thisBit + '\n\n';
  397. }
  398. }
  399. }
  400. // Add authorship block
  401. var authorName = document.getElementById("author-text").value;
  402. var authorURL = document.getElementById("author-url").value;
  403. var authorshipBlock = "---\n\nCreated by ";
  404. if (authorName != "") {
  405. if (authorURL != "") { // both author and URL present
  406. authorshipBlock += ("[" + authorName + "](" + authorURL + ")");
  407. } else { // only authorName present
  408. authorshipBlock += authorName;
  409. }
  410. content += (authorshipBlock + "\n");
  411. }
  412. // Add attribution block
  413. content += document.getElementById('attributionMD').innerHTML;
  414. // Starting here, see https://stackoverflow.com/a/33542499
  415. var blob = new Blob([content], {type: 'text/plain'});
  416. if(window.navigator.msSaveOrOpenBlob) {
  417. window.navigator.msSaveBlob(blob, filename);
  418. }
  419. else{
  420. var elem = window.document.createElement('a');
  421. elem.href = window.URL.createObjectURL(blob);
  422. elem.download = filename;
  423. document.body.appendChild(elem);
  424. elem.click();
  425. document.body.removeChild(elem);
  426. URL.revokeObjectURL(); // This needs an arg but I can't figure out what
  427. }
  428. var myFile = new Blob([fileContent], {type: 'text/plain'});
  429. window.URL = window.URL || window.webkitURL; document.getElementById('download').setAttribute('href',window.URL.createObjectURL(myFile));
  430. document.getElementById('download').setAttribute('download', fileName);
  431. }
  432. // BEGIN Publish tools, via SteinHQ.com
  433. // publishRule()
  434. // Publishes existing fields to new page, /builder/?rule=[ruleID]
  435. // Opens new page in Display mode
  436. function publishRule() {
  437. // Confirm user knows what they're getting into
  438. var r = confirm("Publish to the public Library?");
  439. if (r == false) { return; }
  440. // Proceed with publication
  441. var now = new Date();
  442. // Numerical ID for published Rule
  443. var timeID = now.getTime();
  444. // Readable UTC timestamp
  445. var dateTime = now.getUTCFullYear()+'.'+(now.getUTCMonth()+1)+'.'+now.getUTCDate()
  446. +' '+now.getUTCHours()+":"+ now.getUTCMinutes()+":"+now.getUTCSeconds()
  447. + ' UTC';
  448. // Check if ruleID exists; while yes, replace and repeat
  449. var rule = [{
  450. ruleID: timeID,
  451. timestamp: dateTime,
  452. }];
  453. // begin adding data
  454. // first, RuleBuilder data
  455. document.getElementById("builder-field").innerHTML = ""; // so it doesn't publish
  456. if (!builderEmpty()) {
  457. rule[0]["modules"] = document.getElementById("module-input").innerHTML;
  458. }
  459. // next, RuleWriter data
  460. var fields = document.getElementsByClassName("editable");
  461. for (var i = 0; i < fields.length; i++) {
  462. var key = fields[i].id;
  463. var value = "";
  464. // including input fields
  465. if (fields[i].nodeName == "INPUT") { // for <input>
  466. value = fields[i].value.replace(/(<([^>]+)>)/ig,"");
  467. } else { // for other fields
  468. value = fields[i].innerHTML.replace(/(<([^>]+)>)/ig,"");
  469. }
  470. rule[0][key] = value;
  471. }
  472. // add to lineage (if it is a fork)
  473. if (rID) {
  474. rule[0]["lineage"] = document.getElementById("lineage-list").innerHTML;
  475. }
  476. // add to database
  477. const store = new SteinStore(
  478. "https://api.steinhq.com/v1/storages/5e8b937ab88d3d04ae0816a5"
  479. );
  480. store.append("library", rule).then(data => {
  481. window.open("/create/?r=" + timeID, "_self", false);
  482. });
  483. }
  484. // addLineage
  485. // Adds the current page to the lineage
  486. function addLineage() {
  487. var communityname = document.getElementById("communityname").innerHTML;
  488. var newLineage = " < " + '<a href="/create/?r=' + rID + '">'
  489. + communityname + '</a>';
  490. var oldLineage = document.getElementById("lineage-list").innerHTML;
  491. document.getElementById("lineage-list").innerHTML = newLineage + oldLineage;
  492. }
  493. // fork()
  494. // Forks the current Rule and updates the derivation lineage
  495. function fork() {
  496. document.getElementById("lineage").style.display = "block";
  497. addLineage();
  498. toggleDisplayMode();
  499. }
  500. // displayRule(ID)
  501. // Displays content based on ID
  502. function displayRule(ID) {
  503. const store = new SteinStore(
  504. "https://api.steinhq.com/v1/storages/5e8b937ab88d3d04ae0816a5"
  505. );
  506. (async () => {
  507. var sheets = ["library","templates"];
  508. // create empty set of rules (should only get one member)
  509. var ruleArray = [];
  510. // read values from all sheets
  511. for (var i = 0; i < sheets.length; i++) {
  512. await store.read(sheets[i], { search: { ruleID: ID } }).then(data => {
  513. // test if there's anything in data
  514. if (data.length > 0) {
  515. ruleArray = data;
  516. }
  517. });
  518. }
  519. // Only runs the rest if the array has something
  520. if (ruleArray.length > 0) {
  521. var rule = ruleArray[0];
  522. var fields = document.getElementsByClassName("editable");
  523. for (var i = 0; i < fields.length; i++) {
  524. var key = fields[i].id;
  525. var value = rule[key];
  526. if (typeof value === "undefined") {
  527. value = "";
  528. } else if (key.includes("-")) { // links
  529. document.getElementById(key).value = value;
  530. } else {
  531. document.getElementById(key).innerHTML = value;
  532. }
  533. }
  534. // Add Builder content
  535. document.getElementById("module-input").innerHTML = rule["modules"];
  536. // Add lineage
  537. var lineage = rule["lineage"];
  538. if (typeof lineage === "undefined") {
  539. document.getElementById("lineage-list").innerHTML = "";
  540. } else {
  541. document.getElementById("lineage-list").innerHTML = lineage;
  542. document.getElementById("lineage").display = "block";
  543. }
  544. // Publish timestamp to Rule
  545. document.getElementById('dateTime').innerHTML = rule['timestamp'];
  546. // Finish
  547. displayMode = false;
  548. toggleDisplayMode();
  549. document.title = rule['communityname'] + " / CommunityRule";
  550. }
  551. })();
  552. }
  553. // deleteRule()
  554. // A temporary placeholder that sends an email requesting rule deletion
  555. function deleteRule() {
  556. var urlParamz = new URLSearchParams(window.location.search);
  557. var rID = urlParamz.get('r');
  558. window.open("mailto:medlab@colorado.edu?subject=Delete Rule request ("
  559. + rID + ")&body=Please explain your rationale:\n");
  560. }
  561. // END Publish tools
  562. // FINALLY, Page loading
  563. // First, grab the current URL
  564. var urlParams = new URLSearchParams(window.location.search);
  565. // Determine if it is a published Rule
  566. if (urlParams.has('r')) {
  567. // If so, grab the Rule from database and enter displayMode
  568. var rID = urlParams.get('r');
  569. displayRule(rID);
  570. } else {
  571. // Otherwise, open in editMode as default
  572. var editMode = true;
  573. }
  574. // eqip editable fields to remove formatting from pasted content
  575. window.onload = function() {
  576. var editableElements = document.getElementsByClassName("editable");
  577. for (var i = 0; i < editableElements.length; i++ ) {
  578. editableElements[i].addEventListener("paste", handleEditablePaste);
  579. }
  580. }
  581. </script>