aboutsummaryrefslogtreecommitdiff
path: root/internal/admin/static/hazardeditor.js
blob: 1f5fdf39f6ba276f914efe9152e61ce334ae234e (plain)
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
var hazardData = null;
var hazardID = null;
var expandedCards = {};
var addedSections = {};
var cardWidths = {};

var HAZARD_SECTIONS = [
  {
    id: 'core', label: 'Core', always: true,
    fields: [
      ['name', 'Name', 'text', 'toxic gas'],
      ['description', 'Description', 'textarea', 'A cloud of toxic gas fills the room.', 'wide'],
      ['warn_message', 'Warn Message', 'text', 'The air grows thick with toxic fumes...', 'wide'],
      ['hit_message', 'Hit Message', 'text', 'You cough and choke on the toxic gas!'],
      ['miss_message', 'Miss Message', 'text', 'You hold your breath and avoid the fumes.'],
      ['required_item', 'Required Item', 'search', 'gas_mask', '', null, 'items'],
    ]
  },
  {
    id: 'combat', label: 'Combat', path: 'combat',
    detect: function(d) { return d.combat; },
    fields: [
      ['stats.attack', 'Attack', 'number', '5', 'narrow'],
      ['stats.strength', 'Strength', 'number', '5', 'narrow'],
      ['stats.ranged', 'Ranged', 'number', '1', 'narrow'],
      ['stats.science', 'Science', 'number', '1', 'narrow'],
      ['stats.speed', 'Speed', 'number', '5', 'narrow'],
      ['stats.max_melee_hit', 'Max Melee Hit', 'number', '2', 'narrow'],
      ['stats.max_ranged_hit', 'Max Ranged Hit', 'number', '0', 'narrow'],
      ['stats.max_science_hit', 'Max Science Hit', 'number', '0', 'narrow'],
      ['stats.bonuses.attack_bonus', 'Atk Bonus', 'number', '0', 'narrow'],
      ['stats.bonuses.strength_bonus', 'Str Bonus', 'number', '0', 'narrow'],
      ['stats.bonuses.ranged_bonus', 'Rng Bonus', 'number', '0', 'narrow'],
      ['stats.bonuses.ranged_strength_bonus', 'Rng Str Bonus', 'number', '0', 'narrow'],
      ['stats.bonuses.science_bonus', 'Sci Bonus', 'number', '0', 'narrow'],
      ['stats.bonuses.science_percent_bonus', 'Sci % Bonus', 'number', '0', 'narrow'],
    ]
  }
];

function initHazardEditor() {
  editorType = 'hazards';
  editorFields = [];
  loadList();
  if (window.location.hash) loadHazardEditor(window.location.hash.substring(1));
}

function cardPath(sec) { return sec.path || ''; }

function getVal(data, sec, key) {
  return ced_getVal(data, sec, key);
}

function fieldID(sec, key, idx) {
  return ced_fieldID(sec, key, idx);
}

function setupSearchFields() { ced_setupSearchFields(); }

function collectFieldValue(el, type) { return ced_collectFieldValue(el, type); }

function loadHazardEditor(id) {
  hazardID = id;
  currentID = id;
  renderList('');
  window.location.hash = id;
  API.get('/api/hazards/' + encodeURIComponent(id)).then(function(data) {
    hazardData = data;
    renderHazardEditor(id, data);
  }).catch(function(e) {
    $('#editorMain').innerHTML = '<p style="color:var(--danger)">Failed to load: ' + esc(e.message) + '</p>';
  });
}

function loadItem(id) { loadHazardEditor(id); }

function renderHazardEditor(id, data) {
  var html = renderRenameableHeader('Hazard', id);
  html += '<div class="tabs"><button class="tab active" onclick="switchTab(event,\'fields\')">Fields</button>';
  html += '<button class="tab" onclick="switchTab(event,\'yaml\')">Raw YAML</button></div>';

  html += '<div class="tab-content" id="tabFields">';
  html += '<div class="obj-fields-wrap">';
  HAZARD_SECTIONS.forEach(function(sec) {
    if (!sec.always && sec.detect && !sec.detect(data) && !addedSections[sec.id]) return;
    html += renderCard(sec, data);
  });
  html += '</div>';

  html += '<div class="add-section-bar">';
  html += '<select id="addSectionSelect">';
  html += '<option value="">+ Add Section...</option>';
  HAZARD_SECTIONS.forEach(function(sec) {
    if (sec.always) return;
    if (sec.detect && sec.detect(data)) return;
    if (addedSections[sec.id]) return;
    html += '<option value="' + sec.id + '">' + esc(sec.label) + '</option>';
  });
  html += '</select>';
  html += '<button class="btn btn-primary btn-sm" onclick="addSection()">Add</button>';
  html += renderMoveBar();
  html += '</div>';
  html += '</div>';

  html += '<div class="tab-content" id="tabYaml" style="display:none">';
  html += '<pre>' + esc(data._raw || JSON.stringify(data, null, 2)) + '</pre>';
  html += '</div>';

  html += '<div class="btn-row">';
  html += '<button class="btn btn-primary" onclick="saveHazard()">Save</button>';
  html += '<button class="btn" onclick="duplicateHazard()">Duplicate</button>';
  html += '<button class="btn btn-danger" onclick="deleteHazard()">Remove</button>';
  html += '<button class="btn btn-sm" style="margin-left:auto" onclick="createNewDir()">New Directory</button>';
  html += '</div>';

  $('#editorMain').innerHTML = html;
  setupSearchFields();
}

function renderCurrent() {
  ced_syncDOMToData(hazardData);
  if (!hazardData || !hazardID) return;
  renderHazardEditor(hazardID, hazardData);
}

function renderCard(sec, data) {
  var collapsed = expandedCards[sec.id] === false;
  var isFull = cardWidths[sec.id] !== undefined ? cardWidths[sec.id] : (sec.fullWidth || false);
  var fullClass = isFull ? ' obj-card-full' : '';
  var h = '<div class="obj-card' + fullClass + '" data-card="' + sec.id + '">';
  h += '<div class="obj-card-header" onclick="toggleCard(\'' + sec.id + '\')">';
  h += '<span class="obj-card-arrow">' + (collapsed ? '&#9654;' : '&#9660;') + '</span>';
  h += '<span class="obj-card-label">' + sec.label + '</span>';
  h += '<button class="btn btn-sm obj-card-expand" onclick="event.stopPropagation();toggleCardWidth(\'' + sec.id + '\')" title="' + (isFull ? 'Half width' : 'Full width') + '">' + (isFull ? '\u2190' : '\u2192') + '</button>';
  if (!sec.always) {
    h += '<button class="btn btn-sm btn-danger obj-card-remove" onclick="event.stopPropagation();removeSection(\'' + sec.id + '\')">X</button>';
  }
  h += '</div>';
  if (!collapsed) {
    h += '<div class="obj-card-body">';
    if (sec.id === 'combat') {
      h += renderHazardCombatCard(data);
    } else {
      h += '<div class="obj-card-grid">';
      sec.fields.forEach(function(f) {
        h += renderField(sec, f, data, -1);
      });
      h += '</div>';
      if (sec.id === 'core') {
        h += ced_renderTagHelp('color');
      }
    }
    h += '</div>';
  }
  h += '</div>';
  return h;
}

function renderField(sec, f, data, idx) {
  return ced_renderField(sec, f, data, idx, null, null, cardPath, fieldID, getVal);
}

function toggleCard(id) {
  expandedCards[id] = expandedCards[id] === false ? true : false;
  renderCurrent();
}

function toggleCardWidth(id) {
  cardWidths[id] = !cardWidths[id];
  renderCurrent();
}

function removeSection(id) {
  var sec = HAZARD_SECTIONS.find(function(s) { return s.id === id; });
  if (!sec) return;
  ced_syncDOMToData(hazardData);
  if (sec.path) {
    delete hazardData[sec.path];
  }
  delete addedSections[id];
  renderHazardEditor(hazardID, hazardData);
}

function addSection() {
  var sel = $('#addSectionSelect');
  var id = sel.value;
  if (!id) return;
  var sec = HAZARD_SECTIONS.find(function(s) { return s.id === id; });
  if (!sec) return;

  if (id === 'combat') {
    hazardData.combat = {
      attack_types: ['crush'],
      stats: {
        attack: 1, strength: 0, ranged: 0, science: 0,
        speed: 5,
        max_melee_hit: 0, max_ranged_hit: 0, max_science_hit: 0,
        bonuses: {attack_bonus:0, strength_bonus:0, ranged_bonus:0, ranged_strength_bonus:0, science_bonus:0, science_percent_bonus:0}
      }
    };
  }
  addedSections[id] = true;
  expandedCards[id] = true;
  renderCurrent();
}

function saveHazard() {
  if (!ced_validateFields(HAZARD_SECTIONS, fieldID, null)) return;

  var out = {};
  HAZARD_SECTIONS.forEach(function(sec) {
    var sectionObj = {};
    var hasValues = sec.always;

    if (sec.fields) {
      sec.fields.forEach(function(f) {
        var fid = fieldID(sec, f[0]);
        var el = document.getElementById(fid);
        if (!el) return;
        var val = collectFieldValue(el, f[2]);
        if (val !== '' && val !== false && val !== 0 && val !== null) hasValues = true;
        sectionObj[f[0]] = val;
      });
    }

    if (sec.id === 'combat' && document.getElementById('hz_atktype')) {
      sectionObj['attack_types'] = ced_collectAtkType('hz_atktype');
      hasValues = true;
    }

    if (sec.always) {
      Object.keys(sectionObj).forEach(function(k) { out[k] = sectionObj[k]; });
    } else if (hasValues && sec.path) {
      out[sec.path] = ced_unflattenObj(sectionObj);
    } else if (hasValues && !sec.path) {
      Object.keys(sectionObj).forEach(function(k) { out[k] = sectionObj[k]; });
    }
  });

  ced_cleanOutput(out);
  out.id = hazardID;

  API.put('/api/hazards/' + encodeURIComponent(hazardID), out).then(function(resp) {
    notify('Hazard ' + hazardID + ' saved', 'success');
    updateUndoBar();
    if (resp && resp._raw) hazardData._raw = resp._raw;
  }).catch(function(e) { notify('Save failed: ' + e.message, 'error'); });
}

function deleteHazard() {
  if (!confirm('Delete hazard "' + hazardID + '"?')) return;
  API.del('/api/hazards/' + encodeURIComponent(hazardID)).then(function() {
    notify('Hazard ' + hazardID + ' deleted', 'success');
    updateUndoBar();
    hazardID = null;
    currentID = null;
    hazardData = null;
    $('#editorMain').innerHTML = '<p style="color:#888;text-align:center;margin-top:60px">Deleted</p>';
    loadList();
  }).catch(function(e) { notify('Delete failed: ' + e.message, 'error'); });
}

function duplicateHazard() {
  var baseID = hazardID + '_copy';
  var newID = baseID;
  var counter = 2;
  while (true) {
    var exists = false;
    for (var i = 0; i < allIDs.length; i++) {
      if (allIDs[i] === newID) { exists = true; break; }
    }
    if (!exists) break;
    newID = baseID + '_' + counter;
    counter++;
  }

  var copy = JSON.parse(JSON.stringify(hazardData));
  delete copy._raw;
  delete copy._path;
  copy.id = newID;

  var dir = '';
  if (hazardData._path) {
    var parts = hazardData._path.split('/');
    var parentDir = parts[parts.length - 2];
    if (parentDir !== 'hazards') dir = parentDir;
  }

  API.post('/api/hazards', {id: newID}).then(function() {
    var putOp = API.put('/api/hazards/' + encodeURIComponent(newID), copy);
    if (dir) {
      return putOp.then(function() {
        return API.post('/api/hazards/move', {id: newID, dir: dir});
      });
    }
    return putOp;
  }).then(function() {
    notify('Duplicated as ' + newID, 'success');
    updateUndoBar();
    loadList();
    loadHazardEditor(newID);
  }).catch(function(e) { notify('Duplicate failed: ' + e.message, 'error'); });
}

function renderHazardCombatCard(data) {
  var sec = HAZARD_SECTIONS.find(function(s) { return s.id === 'combat'; });
  if (!sec) return '';
  var byKey = {};
  sec.fields.forEach(function(f) { byKey[f[0]] = f; });

  var h = ced_renderAtkTypeWidget(data, 'hz_atktype', 'ced_atkPillSelect');

  h += '<div class="obj-inline-group">';
  h += '<span class="obj-inline-label">Stats</span>';
  h += '<div class="obj-card-grid" style="margin-top:4px">';
  var statKeys = ['stats.attack','stats.strength','stats.ranged','stats.science'];
  statKeys.forEach(function(k) { h += renderField(sec, byKey[k], data, -1); });
  h += '</div>';
  h += '<div class="obj-card-grid" style="margin-top:4px">';
  h += renderField(sec, byKey['stats.speed'], data, -1);
  h += '</div>';
  h += '<div class="obj-card-grid" style="margin-top:4px">';
  var maxKeys = ['stats.max_melee_hit','stats.max_ranged_hit','stats.max_science_hit'];
  maxKeys.forEach(function(k) { h += renderField(sec, byKey[k], data, -1); });
  h += '</div>';
  h += '</div>';

  h += '<div class="obj-inline-group">';
  h += '<span class="obj-inline-label">Bonuses</span>';
  h += '<div class="obj-card-grid" style="margin-top:4px">';
  var bonusKeys = ['stats.bonuses.attack_bonus','stats.bonuses.strength_bonus','stats.bonuses.ranged_bonus',
    'stats.bonuses.ranged_strength_bonus','stats.bonuses.science_bonus','stats.bonuses.science_percent_bonus'];
  bonusKeys.forEach(function(k) { h += renderField(sec, byKey[k], data, -1); });
  h += '</div>';
  h += '</div>';

  return h;
}