EditNews.vue 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. <script setup lang="ts">
  2. import { defineAsyncComponent, ref, computed, onMounted } from "vue";
  3. import { marked } from "marked";
  4. import DOMPurify from "dompurify";
  5. import Toast from "toasters";
  6. import { formatDistance } from "date-fns";
  7. import { useModalsStore } from "@/stores/modals";
  8. import { useForm } from "@/composables/useForm";
  9. import { useEvents } from "@/composables/useEvents";
  10. import { useModels } from "@/composables/useModels";
  11. import { useWebsocketStore } from "@/stores/websocket";
  12. import { useModelStore } from "@/stores/model";
  13. const Modal = defineAsyncComponent(() => import("@/components/Modal.vue"));
  14. const SaveButton = defineAsyncComponent(
  15. () => import("@/components/SaveButton.vue")
  16. );
  17. const props = defineProps({
  18. modalUuid: { type: String, required: true },
  19. createNews: { type: Boolean, default: false },
  20. newsId: { type: String, default: null },
  21. sector: { type: String, default: "admin" }
  22. });
  23. const { runJob } = useWebsocketStore();
  24. const { findById } = useModelStore();
  25. const { onReady } = useEvents();
  26. const { closeCurrentModal } = useModalsStore();
  27. const { registerModel, onDeleted } = useModels();
  28. const createdBy = ref();
  29. const createdAt = ref(0);
  30. const dataLoaded = ref(false);
  31. const canShow = computed(() => {
  32. if (props.newsId) return dataLoaded.value;
  33. return true;
  34. });
  35. const getTitle = () => {
  36. let title = "";
  37. const preview = document.getElementById("preview");
  38. // validate existence of h1 for the page title
  39. if (!preview || preview.childNodes.length === 0) return "";
  40. if (preview.childNodes[0].nodeName !== "H1") {
  41. for (let node = 0; node < preview.childNodes.length; node += 1) {
  42. if (preview.childNodes[node].nodeName) {
  43. if (preview.childNodes[node].nodeName === "H1")
  44. title = preview.childNodes[node].textContent || "";
  45. break;
  46. }
  47. }
  48. } else title = preview.childNodes[0].textContent || "";
  49. return title;
  50. };
  51. const { inputs, save, setModelValues } = useForm(
  52. {
  53. markdown: {
  54. value: "# Header\n## Sub-Header\n- **So**\n- _Many_\n- ~Points~\n\nOther things you want to say and [link](https://example.com).\n\n### Sub-Sub-Header\n> Oh look, a quote!\n\n`lil code`\n\n```\nbig code\n```\n",
  55. validate: (value: string) => {
  56. if (value === "") return "News item cannot be empty.";
  57. if (!getTitle())
  58. return "Please provide a title (heading level 1) at the top of the document.";
  59. return true;
  60. }
  61. },
  62. status: "published",
  63. showToNewUsers: false
  64. },
  65. ({ status, messages, values }, resolve, reject) => {
  66. if (status === "success") {
  67. const query = {
  68. title: getTitle(),
  69. markdown: values.markdown,
  70. status: values.status,
  71. showToNewUsers: values.showToNewUsers
  72. };
  73. const method = props.createNews
  74. ? runJob(`data.news.create`, { query })
  75. : runJob(`data.news.updateById`, { _id: props.newsId, query });
  76. method.then(resolve).catch(reject);
  77. } else {
  78. if (status === "unchanged") new Toast(messages.unchanged);
  79. else if (status === "error")
  80. Object.values(messages).forEach(message => {
  81. new Toast({ content: message, timeout: 8000 });
  82. });
  83. resolve();
  84. }
  85. },
  86. {
  87. modalUuid: props.modalUuid
  88. }
  89. );
  90. onMounted(async () => {
  91. marked.use({
  92. renderer: {
  93. table(header, body) {
  94. return `<table class="table">
  95. <thead>${header}</thead>
  96. <tbody>${body}</tbody>
  97. </table>`;
  98. }
  99. }
  100. });
  101. await onReady(async () => {
  102. if (props.newsId && !props.createNews) {
  103. const data = await findById("news", props.newsId).catch(() => {
  104. new Toast("News with that ID not found.");
  105. closeCurrentModal();
  106. });
  107. if (!data) return;
  108. const model = await registerModel(data, { news: "createdBy" });
  109. setModelValues(model, ["markdown", "status", "showToNewUsers"]);
  110. createdBy.value = model.createdBy;
  111. createdAt.value = model.createdAt;
  112. dataLoaded.value = true;
  113. await onDeleted("news", ({ oldDoc }) => {
  114. if (oldDoc._id !== props.newsId) return;
  115. new Toast("News item has been deleted.");
  116. closeCurrentModal();
  117. });
  118. }
  119. });
  120. });
  121. </script>
  122. <template>
  123. <modal
  124. class="edit-news-modal"
  125. :title="createNews ? 'Create News' : 'Edit News'"
  126. :size="'wide'"
  127. :split="true"
  128. >
  129. <template #body>
  130. <div class="left-section" v-show="canShow">
  131. <p><strong>Markdown</strong></p>
  132. <textarea v-model="inputs['markdown'].value"></textarea>
  133. </div>
  134. <div class="right-section" v-show="canShow">
  135. <p><strong>Preview</strong></p>
  136. <div
  137. class="news-item"
  138. id="preview"
  139. v-html="
  140. DOMPurify.sanitize(marked(inputs['markdown'].value))
  141. "
  142. ></div>
  143. </div>
  144. </template>
  145. <template #footer>
  146. <div>
  147. <p class="control select">
  148. <select v-model="inputs['status'].value">
  149. <option value="draft">Draft</option>
  150. <option value="published" selected>Publish</option>
  151. </select>
  152. </p>
  153. <p class="is-expanded checkbox-control">
  154. <label class="switch">
  155. <input
  156. type="checkbox"
  157. id="show-to-new-users"
  158. v-model="inputs['showToNewUsers'].value"
  159. />
  160. <span class="slider round"></span>
  161. </label>
  162. <label for="show-to-new-users">
  163. <p>Show to new users</p>
  164. </label>
  165. </p>
  166. <save-button
  167. ref="saveButton"
  168. v-if="createNews"
  169. @clicked="save()"
  170. />
  171. <save-button
  172. ref="saveAndCloseButton"
  173. default-message="Save and close"
  174. @clicked="save(closeCurrentModal)"
  175. />
  176. <div class="right" v-if="createdAt > 0">
  177. <span>
  178. By&nbsp;
  179. <router-link
  180. :to="{ path: `/u/${createdBy.username}` }"
  181. :title="createdBy._id"
  182. >
  183. {{ createdBy.name }}
  184. </router-link></span
  185. >&nbsp;<span :title="new Date(createdAt).toString()">
  186. {{
  187. formatDistance(createdAt, new Date(), {
  188. addSuffix: true
  189. })
  190. }}
  191. </span>
  192. </div>
  193. </div>
  194. </template>
  195. </modal>
  196. </template>
  197. <style lang="less">
  198. .edit-news-modal .modal-card .modal-card-foot .right {
  199. column-gap: 5px;
  200. }
  201. </style>
  202. <style lang="less" scoped>
  203. .night-mode {
  204. .edit-news-modal .modal-card .modal-card-body textarea,
  205. .edit-news-modal .modal-card .modal-card-body #preview {
  206. border-color: var(--grey-3);
  207. }
  208. .edit-news-modal .modal-card .modal-card-body textarea {
  209. background-color: var(--dark-grey);
  210. color: var(--white);
  211. }
  212. }
  213. .edit-news-modal .modal-card .modal-card-body {
  214. .left-section,
  215. .right-section {
  216. padding: 10px;
  217. }
  218. textarea {
  219. border: 0;
  220. outline: none;
  221. resize: none;
  222. font-size: 16px;
  223. }
  224. #preview {
  225. word-break: break-all;
  226. overflow: auto;
  227. box-shadow: 0;
  228. }
  229. textarea,
  230. #preview {
  231. padding: 5px;
  232. border: 1px solid var(--light-grey-3) !important;
  233. border-radius: @border-radius;
  234. height: calc(100vh - 280px);
  235. width: 100%;
  236. }
  237. }
  238. .edit-news-modal .modal-card .modal-card-foot {
  239. .control {
  240. margin-bottom: 0 !important;
  241. }
  242. .right {
  243. line-height: 36px;
  244. column-gap: 0;
  245. }
  246. }
  247. </style>