-
Notifications
You must be signed in to change notification settings - Fork 9
/
iconcheckbox.js
96 lines (75 loc) · 2.97 KB
/
iconcheckbox.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
(function iconcheckMacro() {
// usage:
// <<iconcheck $isSomething>>toggle value<</iconcheck>>
// <<iconcheck $isSomething "Turn on" "Turn off">><</iconcheck>>
'use strict';
/* globals version, Macro, Wikifier, State */
const macroName = 'iconcheck';
if (!version || !version.title || 'SugarCube' !== version.title || !version.major || version.major < 2) {
throw new Error(`<<${macroName}>> macro requires SugarCube 2.0 or greater, aborting load`);
}
version.extensions.abbr = {major: 1, minor: 0, revision: 0};
const clsPrefix = 'iconcheck';
const styles = `
.${macroName} {
cursor: pointer;
}
.${macroName} input {
visibility: hidden;
}
.${macroName} input + span::before {
font-family: tme-fa-icons;
content: '\\e830\\00a0';
}
.${macroName} input:checked + span::before {
content: '\\e831\\00a0';
}
`;
jQuery('head').append(`<style type="text/css" id="${macroName}-style">${styles}</style>`);
Macro.add(macroName, {
tags: null,
handler () {
const {args, payload} = this;
// Ensure that the variable name argument is a string.
if (typeof args[0] !== 'string') {
return this.error('variable name argument is not a string');
}
let varName = args[0].trim();
// Try to ensure that we receive the variable's name (incl. sigil), not its value.
if (varName[0] !== '$' && varName[0] !== '_') {
return this.error(`variable name "${args[0]}" is missing its sigil ($ or _)`);
}
varName = varName.substring(1);
let onChange = null;
if (args[3]) {
if (typeof args[3] === 'function') {
onChange = args[3];
} else if (typeof args[3] === 'string' && window[args[3]]) {
onChange = window[args[3]];
}
}
const $span = jQuery('<span></span>');
const $input = jQuery(`<input type="checkbox" ${State.variables[varName] ? 'checked' : ''}/>`);
$input.on('change', () => {
const value = $input.prop('checked');
State.variables[varName] = value;
$span.html(getLabel());
if (onChange) {
onChange(value);
}
});
function getLabel() {
if (args.length >= 3) {
return State.variables[varName] ? args[1] : args[2];
} else {
return payload[0].contents;
}
}
new Wikifier($span, getLabel());
const $label = jQuery(`<label class="${clsPrefix}"></label>`);
$input.appendTo($label);
$span.appendTo($label);
$label.appendTo(this.output);
},
});
}());