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