-
Notifications
You must be signed in to change notification settings - Fork 28
/
getSetting.tid
executable file
·109 lines (91 loc) · 2.61 KB
/
getSetting.tid
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
97
98
99
100
101
102
103
104
105
106
107
108
109
/*\
title: $:/plugins/OokTech/Bob/macros/getSetting.js
type: application/javascript
module-type: macro
/*
Macro to return the value of a setting in the settings json structure
This is needed because tiddlywiki doesn't support nested json objects and
the settings structure is faking it.
This is done relative to the tiddler given by the root parameter.
To fit with tiddlywiki as much as possible each level is separated by ##
{
First: {
Second: {
Item: Value
}
}
}
Given the above JSON you could use this:
<<getSetting key="First##Second##Item">>
which would return Value
Note that this returns the first leaf reached. If you add extra levels that
don't exit to the end of the key they are ignored. So in the example if you
used First##Second##Item##this##changes##nothing than it would work the same
way.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Information about this macro
*/
exports.name = "getSetting";
exports.params = [
{name: "key"},
{name: "root"}
];
/*
Run the macro
*/
exports.run = function(key, root) {
if(!key) {
// If no key is given return an empty string.
return "";
} else {
// Split the key up into it separate parts.
var keys = key.split('##');
}
// If no root is given use the default.
if(!root) {
root = "$:/WikiSettings/split";
}
var tiddler = $tw.wiki.getTiddler(root);
if(!tiddler) {
// if the root doesn't exist return an empty string.
return "";
}
// Walk through the settings to find the desired key and return it.
return walk(keys, tiddler);
};
/*
This function walks though each property in the json from the tiddler text and
either returns the value indicated by the next key or, if the value is a
tiddler title in the correct form, calls itself again with the next key and
tiddler.
*/
function walk(keys, tiddler) {
try {
var currentLevel = JSON.parse(tiddler.fields.text);
if(typeof currentLevel[keys[0]] === 'string') {
// If the current level is a tiddler holding the next nested object pass
// that into the walk function, otherwise return the value of the key at
// this level.
if(currentLevel[keys[0]].startsWith(tiddler.fields.title)) {
var newTiddler = $tw.wiki.getTiddler(currentLevel[keys[0]]);
keys.shift();
return walk(keys, newTiddler);
} else {
return currentLevel[keys[0]];
}
} else {
// If we run into an invalid key, or one that doesn't exist return an
// empty string.
return "";
}
} catch (e) {
// If parsing fails return an empty string.
return "";
}
}
})();