Path: blob/master/src/packages/frontend/editors/task-editor/desc-rendering.ts
1691 views
/*1* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.2* License: MS-RSL – see LICENSE.md for details3*/45/*6Utility/parsing functions used in rendering task description.7*/89import { replace_all_function, parse_hashtags } from "@cocalc/util/misc";10import { apply_without_math } from "@cocalc/util/mathjax-utils-2";11import { SelectedHashtags } from "./types";1213// Make clever use of replace_all_function to toggle the state of a checkbox.14export function toggle_checkbox(s, index, checked): string {15// Find the index'd checkbox and change the state to not checked.16let cur, next;17if (checked) {18cur = "[x]";19next = "[ ]";20} else {21cur = "[ ]";22next = "[x]";23}2425return apply_without_math(s, (x) =>26replace_all_function(x, cur, function (i) {27if (i === index) {28return next;29} else {30return cur;31}32})33);34}3536// assumes value is the text output by remove_math!37export function process_hashtags(38value: string,39selected_hashtags?: SelectedHashtags40): string {41// replace hashtags by a span with appropriate class42const v = parse_hashtags(value);43if (v.length === 0) {44return value;45}46// replace hashtags by something that renders nicely in markdown (instead of as descs)47let x0 = [0, 0];48let value0 = "";49for (let x of v) {50const hashtag = value.slice(x[0] + 1, x[1]);51const state = selected_hashtags?.get(hashtag);52let cls = "ant-tag ant-tag-checkable ";53let bgcolor = "";54if (state === 1) {55cls = "ant-tag ant-tag-checkable ant-tag-checkable-checked";56} else {57bgcolor = "background-color:white;";58}59value0 +=60value.slice(x0[1], x[0]) +61`<span style='border:1px solid #ddd;border-radius:5px;font-size:inherit;${bgcolor}' class='${cls}' data-hashtag='${hashtag}' data-state='${state}'>#` +62hashtag +63"</span>";64x0 = x;65}66return value0 + value.slice(x0[1]);67}6869// assumes value is the text output by remove_math!70export function process_checkboxes(value) {71value = replace_all_function(72value,73"[ ]",74(index) => `<span data-index='${index}' data-checkbox='false' style='cursor:pointer'>☐<span>`75);76value = replace_all_function(77value,78"[x]",79(index) => `<span data-index='${index}' data-checkbox='true' style='cursor:pointer'>☑<span>`80);81return value;82}8384export function header_part(s) {85const lines = s.trim().split("\n");86for (87let i = 0, end = lines.length, asc = 0 <= end;88asc ? i < end : i > end;89asc ? i++ : i--90) {91if (lines[i].trim() === "") {92if (i === lines.length - 1) {93return s;94} else {95return lines.slice(0, i).join("\n");96}97}98}99return s;100}101102103