1 local setmetatable = setmetatable;
2 local pairs, ipairs = pairs, ipairs;
3 local tostring, type = tostring, type;
4 local t_concat = table.concat;
6 local st = require "util.stanza";
10 local xmlns_forms = 'jabber:x:data';
13 local form_mt = { __index = form_t };
16 return setmetatable(layout, form_mt);
19 local form_x_attr = { xmlns = xmlns_forms };
21 function form_t.form(layout, data)
22 local form = st.stanza("x", form_x_attr);
24 form:tag("title"):text(layout.title):up();
26 if layout.instructions then
27 form:tag("instructions"):text(layout.instructions):up();
29 for n, field in ipairs(layout) do
30 local field_type = field.type or "text-single";
32 form:tag("field", { type = field_type, var = field.name, label = field.label });
34 local value = data[field.name];
36 -- Add value, depending on type
37 if field_type == "hidden" then
38 if type(value) == "table" then
39 -- Assume an XML snippet
44 form:tag("value"):text(tostring(value)):up();
46 elseif field_type == "boolean" then
47 form:tag("value"):text((value and "1") or "0"):up();
48 elseif field_type == "fixed" then
50 elseif field_type == "jid-multi" then
51 for _, jid in ipairs(value) do
52 form:tag("value"):text(jid):up();
54 elseif field_type == "jid-single" then
55 form:tag("value"):text(value):up();
56 elseif field_type == "text-single" or field_type == "text-private" then
57 form:tag("value"):text(value):up();
58 elseif field_type == "text-multi" then
59 -- Split into multiple <value> tags, one for each line
60 for line in value:gmatch("([^\r\n]+)\r?\n*") do
61 form:tag("value"):text(line):up();
65 if field.required then
66 form:tag("required"):up();
69 -- Jump back up to list of fields
75 local field_readers = {};
77 function form_t.data(layout, stanza)
80 for field_tag in stanza:childtags() do
81 local field_type = field_tag.attr.type;
83 local reader = field_readers[field_type];
85 data[field_tag.attr.var] = reader(field_tag);
92 field_readers["text-single"] =
94 local value = field_tag:child_with_name("value");
100 field_readers["text-private"] =
101 field_readers["text-single"];
103 field_readers["text-multi"] =
106 for value_tag in field_tag:childtags() do
107 if value_tag.name == "value" then
108 result[#result+1] = value_tag[1];
111 return t_concat(result, "\n");
114 field_readers["boolean"] =
116 local value = field_tag:child_with_name("value");
118 if value[1] == "1" or value[1] == "true" then
126 field_readers["hidden"] =
128 local value = field_tag:child_with_name("value");
142 title = "MUC Configuration",
143 instructions = [[Use this form to configure options for this MUC room.]],
145 { name = "FORM_TYPE", type = "hidden", required = true };
146 { name = "field-name", type = "field-type", required = false };