app.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878
  1. /*
  2. app.js
  3. Boots the builder and wires everything together: the icon rail, the top bar,
  4. the status bar, keyboard shortcuts, node level commands (insert, duplicate,
  5. wrap, delete), autosave, and the ArozOS integration (input files, window
  6. title, desktop theme).
  7. Module load order matters and is fixed in index.html:
  8. icons - schema - model - render - ui - canvas - panels - fileio -
  9. publish - settings - app
  10. */
  11. var WBApp = (function () {
  12. var activePanel = "add";
  13. var dockCollapsed = false;
  14. var autosave = true;
  15. var autosaveTimer = null;
  16. var styleClipboard = null;
  17. var suppressPanelRefresh = false;
  18. /* ------------------------------------------------------------ boot -- */
  19. function init() {
  20. applyTheme();
  21. WBModel.newProject("My Website");
  22. WBCanvas.init({
  23. onSelect: function (id) { selectNode(id, { fromCanvas: true }); },
  24. onHover: function (id) { WBLayers.setHover(id); },
  25. onChange: onCanvasChange,
  26. onEditStateChange: onEditStateChange,
  27. onRequestMenu: function (id, pos) { showElementMenu(id, pos); }
  28. });
  29. WBInspector.init();
  30. WBPalette.init();
  31. WBPages.init();
  32. WBLayers.init();
  33. WBDesign.init();
  34. WBSettings.init();
  35. bindRail();
  36. bindTopbar();
  37. bindStatusbar();
  38. bindTextToolbar();
  39. bindShortcuts();
  40. bindHelp();
  41. WBModel.on("change", onModelChange);
  42. WBModel.on("restore", onModelRestore);
  43. WBModel.on("clean", updateSaveState);
  44. WBCanvas.setDevice("base");
  45. WBCanvas.render();
  46. setTimeout(function () { WBCanvas.zoomToFit(); updateZoomLabel(); }, 120);
  47. selectNode(null);
  48. refreshTitles();
  49. updateSaveState();
  50. loadInputFile();
  51. }
  52. /* Open the file the desktop launched us with, when there is one. */
  53. function loadInputFile() {
  54. var inputFiles = null;
  55. try { inputFiles = ao_module_loadInputFiles(); } catch (e) { inputFiles = null; }
  56. if (!inputFiles || !inputFiles.length) { return; }
  57. var f = inputFiles[0];
  58. WBFileIO.openPath(f.filepath, function (ok) {
  59. if (!ok) { return; }
  60. afterProjectLoaded();
  61. });
  62. }
  63. function afterProjectLoaded() {
  64. WBCanvas.render();
  65. selectNode(null);
  66. WBPages.render();
  67. WBLayers.render();
  68. WBDesign.render();
  69. WBSettings.render();
  70. refreshTitles();
  71. updateSaveState();
  72. setTimeout(function () { WBCanvas.zoomToFit(); updateZoomLabel(); }, 100);
  73. }
  74. /* ------------------------------------------------------------ rail -- */
  75. function bindRail() {
  76. var btns = document.querySelectorAll("#wb-rail .wb-rail-btn");
  77. for (var i = 0; i < btns.length; i++) {
  78. (function (btn) {
  79. btn.addEventListener("click", function () {
  80. var panel = btn.getAttribute("data-panel");
  81. if (panel === activePanel && !dockCollapsed) {
  82. dockCollapsed = true;
  83. document.getElementById("wb-leftdock").classList.add("collapsed");
  84. } else {
  85. dockCollapsed = false;
  86. document.getElementById("wb-leftdock").classList.remove("collapsed");
  87. showPanel(panel);
  88. }
  89. setTimeout(function () { WBCanvas.scheduleOverlayUpdate(); }, 30);
  90. });
  91. })(btns[i]);
  92. }
  93. }
  94. function showPanel(name) {
  95. activePanel = name;
  96. var panels = document.querySelectorAll(".wb-panel");
  97. for (var i = 0; i < panels.length; i++) {
  98. panels[i].classList.toggle("active", panels[i].id === "wb-panel-" + name);
  99. }
  100. var btns = document.querySelectorAll("#wb-rail .wb-rail-btn");
  101. for (var j = 0; j < btns.length; j++) {
  102. btns[j].classList.toggle("active", btns[j].getAttribute("data-panel") === name);
  103. }
  104. if (name === "layers") { WBLayers.render(); WBLayers.revealSelected(); }
  105. if (name === "pages") { WBPages.render(); }
  106. if (name === "design") { WBDesign.render(); }
  107. if (name === "settings") { WBSettings.render(); }
  108. }
  109. /* ---------------------------------------------------------- topbar -- */
  110. function bindTopbar() {
  111. document.getElementById("wb-project-btn").addEventListener("click", function (e) {
  112. WBUI.menu(e.currentTarget, [
  113. { header: "Project" },
  114. { label: "New Site", icon: "new-file", action: newSite },
  115. { label: "Open...", icon: "open", key: "Ctrl+O", action: openSite },
  116. { label: "Save", icon: "save", key: "Ctrl+S", action: save },
  117. { label: "Save As...", icon: "duplicate", action: saveAs },
  118. { separator: true },
  119. { label: "Rename Site", icon: "pencil", action: renameSite },
  120. { label: "Import HTML As Page", icon: "download", action: function () {
  121. WBFileIO.importHtmlAsPage();
  122. } }
  123. ]);
  124. });
  125. var devBtns = document.querySelectorAll("[data-device]");
  126. for (var i = 0; i < devBtns.length; i++) {
  127. (function (b) {
  128. b.addEventListener("click", function () { setDevice(b.getAttribute("data-device")); });
  129. })(devBtns[i]);
  130. }
  131. document.getElementById("wb-undo").addEventListener("click", undo);
  132. document.getElementById("wb-redo").addEventListener("click", redo);
  133. document.getElementById("wb-preview-btn").addEventListener("click", function () {
  134. WBPublish.togglePreview();
  135. });
  136. document.getElementById("wb-exit-preview").addEventListener("click", function () {
  137. WBPublish.togglePreview(false);
  138. });
  139. document.getElementById("wb-publish-btn").addEventListener("click", function () {
  140. WBPublish.publish();
  141. });
  142. document.getElementById("wb-more-btn").addEventListener("click", function (e) {
  143. WBUI.menu(e.currentTarget, [
  144. { label: "Preview In New Tab", icon: "external", action: WBPublish.openInNewTab },
  145. { label: "Publish...", icon: "publish", action: WBPublish.publish },
  146. { label: "Export To Folder...", icon: "download", action: WBPublish.exportToFolder },
  147. { separator: true },
  148. { label: "Site Settings", icon: "gear", action: function () { showPanel("settings"); openDock(); } },
  149. { label: "Personal Site Settings", icon: "globe", action: function () {
  150. try { ao_module_openSetting("Network", "Personal Page"); }
  151. catch (err) { WBUI.toast("Open ArozOS Settings > Network > Personal Page", "err"); }
  152. } },
  153. { separator: true },
  154. { label: "Zoom To Fit", icon: "resize", key: "Ctrl+0", action: function () {
  155. WBCanvas.zoomToFit(); updateZoomLabel();
  156. } },
  157. { label: "Keyboard Shortcuts", icon: "help", action: showShortcuts },
  158. { label: "About Site Builder", icon: "info", action: showAbout }
  159. ], { alignRight: true });
  160. });
  161. }
  162. function openDock() {
  163. dockCollapsed = false;
  164. document.getElementById("wb-leftdock").classList.remove("collapsed");
  165. }
  166. function setDevice(key) {
  167. WBCanvas.setDevice(key);
  168. var all = document.querySelectorAll("[data-device]");
  169. for (var i = 0; i < all.length; i++) {
  170. all[i].classList.toggle("active", all[i].getAttribute("data-device") === key);
  171. }
  172. updateZoomLabel();
  173. WBInspector.render();
  174. }
  175. /* ------------------------------------------------------- status bar -- */
  176. function bindStatusbar() {
  177. document.getElementById("wb-zoom-out").addEventListener("click", function () {
  178. WBCanvas.setZoom(WBCanvas.getZoom() - 0.1);
  179. updateZoomLabel();
  180. });
  181. document.getElementById("wb-zoom-in").addEventListener("click", function () {
  182. WBCanvas.setZoom(WBCanvas.getZoom() + 0.1);
  183. updateZoomLabel();
  184. });
  185. document.getElementById("wb-zoom-label").addEventListener("click", function () {
  186. WBCanvas.setZoom(1);
  187. updateZoomLabel();
  188. });
  189. }
  190. function updateZoomLabel() {
  191. document.getElementById("wb-zoom-label").textContent =
  192. Math.round(WBCanvas.getZoom() * 100) + "%";
  193. }
  194. function renderBreadcrumb() {
  195. var el = document.getElementById("wb-breadcrumb");
  196. WBUI.clear(el);
  197. var id = WBCanvas.getSelection();
  198. var chain = id ? (WBModel.pathTo(id) || []) : [];
  199. if (!chain.length) {
  200. el.appendChild(WBUI.el("span", { class: "wb-crumb", text: WBModel.activePage().name }));
  201. return;
  202. }
  203. chain.forEach(function (n, i) {
  204. if (i) { el.appendChild(WBUI.el("span", { class: "wb-crumb-sep", html: WBIcon("caret-right", 9) })); }
  205. el.appendChild(WBUI.el("button", {
  206. class: "wb-crumb" + (i === chain.length - 1 ? " current" : ""),
  207. type: "button",
  208. text: WBModel.displayName(n),
  209. onclick: function () { selectNode(n.id); }
  210. }));
  211. });
  212. }
  213. /* ------------------------------------------------- canvas callbacks -- */
  214. function onCanvasChange(evt) {
  215. switch (evt.action) {
  216. case "insert":
  217. insertElement(evt.type, evt.parentId, evt.index);
  218. break;
  219. case "move":
  220. if (WBModel.moveNode(evt.id, evt.parentId, evt.index)) {
  221. WBModel.commit("Move element");
  222. rerenderCanvas();
  223. selectNode(evt.id);
  224. }
  225. break;
  226. case "delete":
  227. deleteNode(evt.id);
  228. break;
  229. case "text":
  230. case "resize":
  231. WBLayers.render();
  232. WBInspector.render();
  233. updateSaveState();
  234. break;
  235. default:
  236. break;
  237. }
  238. }
  239. function onEditStateChange(editing) {
  240. var bar = document.getElementById("wb-text-toolbar");
  241. bar.classList.toggle("editing", editing);
  242. updateTextToolbarState();
  243. }
  244. function onModelChange() {
  245. updateSaveState();
  246. updateHistoryButtons();
  247. scheduleAutosave();
  248. }
  249. function onModelRestore() {
  250. rerenderCanvas();
  251. var id = WBCanvas.getSelection();
  252. if (id && !WBModel.findNode(id)) { id = null; }
  253. selectNode(id, { silentCanvas: false });
  254. WBPages.render();
  255. WBDesign.render();
  256. refreshTitles();
  257. updateSaveState();
  258. updateHistoryButtons();
  259. }
  260. /* --------------------------------------------------- node commands -- */
  261. /*
  262. Insert a new element. When no explicit parent is given the element goes
  263. into the current selection if it can hold children, otherwise right
  264. after the selection, otherwise at the end of the page.
  265. */
  266. function insertElement(type, parentId, index) {
  267. var node = WBModel.createNode(type);
  268. if (parentId === undefined || parentId === null) {
  269. var selId = WBCanvas.getSelection();
  270. var sel = selId ? WBModel.findNode(selId) : null;
  271. if (sel && (wbIsContainer(sel.type) || sel.type === "body")) {
  272. parentId = sel.id;
  273. index = sel.children.length;
  274. } else if (sel) {
  275. var parent = WBModel.findParent(sel.id);
  276. parentId = parent ? parent.id : WBModel.activePage().root.id;
  277. index = WBModel.indexOfNode(sel.id) + 1;
  278. } else {
  279. parentId = WBModel.activePage().root.id;
  280. index = null;
  281. }
  282. }
  283. if (!WBModel.insertNode(parentId, node, index)) {
  284. WBUI.toast("That element cannot hold other elements", "err");
  285. return;
  286. }
  287. WBModel.commit("Add " + wbDef(type).name);
  288. rerenderCanvas();
  289. selectNode(node.id);
  290. WBCanvas.scrollToNode(node.id);
  291. if (wbIsTextEditable(type)) {
  292. setTimeout(function () { WBCanvas.startTextEdit(node.id); }, 120);
  293. }
  294. }
  295. function deleteNode(id) {
  296. var node = WBModel.findNode(id);
  297. if (!node || node.type === "body") { return; }
  298. var parent = WBModel.findParent(id);
  299. var idx = WBModel.indexOfNode(id);
  300. WBCanvas.stopTextEdit();
  301. WBModel.removeNode(id);
  302. WBModel.commit("Delete " + WBModel.displayName(node));
  303. rerenderCanvas();
  304. var next = null;
  305. if (parent) {
  306. next = parent.children[Math.min(idx, parent.children.length - 1)];
  307. }
  308. selectNode(next ? next.id : (parent ? parent.id : null));
  309. }
  310. function duplicateNode(id) {
  311. var copy = WBModel.duplicateNode(id);
  312. if (!copy) { return; }
  313. WBModel.commit("Duplicate element");
  314. rerenderCanvas();
  315. selectNode(copy.id);
  316. }
  317. function wrapInContainer(id) {
  318. var node = WBModel.findNode(id);
  319. var parent = WBModel.findParent(id);
  320. if (!node || !parent) { return; }
  321. var idx = WBModel.indexOfNode(id);
  322. var box = WBModel.createNode("container");
  323. box.styles.base = { maxWidth: "none", marginLeft: "0", marginRight: "0", width: "100%" };
  324. parent.children.splice(idx, 1, box);
  325. box.children.push(node);
  326. WBModel.commit("Wrap in container");
  327. rerenderCanvas();
  328. selectNode(box.id);
  329. }
  330. function unwrapNode(id) {
  331. var node = WBModel.findNode(id);
  332. var parent = WBModel.findParent(id);
  333. if (!node || !parent || node.type === "body") { return; }
  334. var idx = WBModel.indexOfNode(id);
  335. var args = [idx, 1].concat(node.children);
  336. Array.prototype.splice.apply(parent.children, args);
  337. WBModel.commit("Unwrap element");
  338. rerenderCanvas();
  339. selectNode(node.children.length ? node.children[0].id : parent.id);
  340. }
  341. function copyStyles(id) {
  342. var node = WBModel.findNode(id);
  343. if (!node) { return; }
  344. styleClipboard = WBModel.clone(node.styles);
  345. WBUI.toast("Styles copied - select another element and press Ctrl+Shift+V");
  346. }
  347. function pasteStyles(id) {
  348. if (!styleClipboard) { WBUI.toast("No styles copied yet", "err"); return; }
  349. var node = WBModel.findNode(id);
  350. if (!node) { return; }
  351. node.styles = WBModel.clone(styleClipboard);
  352. WBModel.commit("Paste styles");
  353. WBCanvas.refreshStyles();
  354. WBInspector.render();
  355. }
  356. function showElementMenu(id, pos) {
  357. var node = WBModel.findNode(id);
  358. if (!node) { return; }
  359. var parent = WBModel.findParent(id);
  360. WBUI.menu(pos || { x: 200, y: 200 }, [
  361. { label: "Duplicate", icon: "duplicate", key: "Ctrl+D", action: function () { duplicateNode(id); } },
  362. { label: "Copy Styles", icon: "copy", action: function () { copyStyles(id); } },
  363. { label: "Paste Styles", icon: "palette", disabled: !styleClipboard,
  364. action: function () { pasteStyles(id); } },
  365. { separator: true },
  366. { label: "Select Parent", icon: "caret-up", disabled: !parent,
  367. action: function () { selectNode(parent.id); } },
  368. { label: "Wrap In Container", icon: "container", action: function () { wrapInContainer(id); } },
  369. { separator: true },
  370. { label: "Delete", icon: "trash", danger: true, key: "Del",
  371. disabled: node.type === "body", action: function () { deleteNode(id); } }
  372. ]);
  373. }
  374. /* ------------------------------------------------------- selection -- */
  375. function selectNode(id, opts) {
  376. opts = opts || {};
  377. if (!opts.fromCanvas) { WBCanvas.select(id, { silent: true }); }
  378. WBInspector.setTarget(id);
  379. renderBreadcrumb();
  380. if (!suppressPanelRefresh) {
  381. WBLayers.render();
  382. if (!opts.fromLayers) { WBLayers.revealSelected(); }
  383. }
  384. }
  385. function highlightNode(id) {
  386. WBLayers.setHover(id);
  387. }
  388. /* ---------------------------------------------------------- canvas -- */
  389. function rerenderCanvas(opts) {
  390. opts = opts || {};
  391. if (opts.soft) { WBCanvas.refreshStyles(); }
  392. else { WBCanvas.render(); }
  393. WBCanvas.select(WBCanvas.getSelection(), { silent: true, force: true });
  394. suppressPanelRefresh = true;
  395. WBLayers.render();
  396. suppressPanelRefresh = false;
  397. renderBreadcrumb();
  398. }
  399. function refreshInspector() { WBInspector.render(); }
  400. /* ----------------------------------------------------------- pages -- */
  401. function switchPage(id) {
  402. WBCanvas.stopTextEdit();
  403. WBModel.setActivePage(id);
  404. WBCanvas.render();
  405. selectNode(null);
  406. WBPages.render();
  407. WBLayers.render();
  408. WBDesign.render();
  409. refreshTitles();
  410. setTimeout(function () { WBCanvas.syncFrameHeight(); WBCanvas.updateOverlay(); }, 120);
  411. }
  412. /* ------------------------------------------------------ file state -- */
  413. function refreshTitles() {
  414. var project = WBModel.get();
  415. document.getElementById("wb-project-name").textContent = project.name;
  416. var page = WBModel.activePage();
  417. try {
  418. ao_module_setWindowTitle(project.name + " - " + page.name + " - Site Builder");
  419. } catch (e) { /* not running inside the ArozOS desktop */ }
  420. document.title = project.name + " - Site Builder";
  421. WBPages.renderSettings();
  422. }
  423. function updateSaveState() {
  424. var dirty = WBModel.isDirty();
  425. var st = document.getElementById("wb-save-state");
  426. st.classList.toggle("dirty", dirty);
  427. st.querySelector(".wb-save-icon").innerHTML = WBIcon(dirty ? "cloud-off" : "cloud-check", 15);
  428. st.querySelector(".wb-save-text").textContent = dirty ? "Unsaved" : "Saved";
  429. document.getElementById("wb-status-dot").classList.toggle("dirty", dirty);
  430. document.getElementById("wb-status-saved").textContent =
  431. dirty ? "Unsaved changes" : (WBFileIO.currentPath() ? "Saved to " + WBFileIO.fileName() : "Not saved yet");
  432. }
  433. function updateHistoryButtons() {
  434. document.getElementById("wb-undo").disabled = !WBModel.canUndo();
  435. document.getElementById("wb-redo").disabled = !WBModel.canRedo();
  436. }
  437. function scheduleAutosave() {
  438. if (!autosave || !WBFileIO.currentPath()) { return; }
  439. if (autosaveTimer) { clearTimeout(autosaveTimer); }
  440. autosaveTimer = setTimeout(function () {
  441. if (!WBModel.isDirty()) { return; }
  442. WBFileIO.save(function (ok) {
  443. if (ok) { updateSaveState(); }
  444. });
  445. }, 4000);
  446. }
  447. function getAutosave() { return autosave; }
  448. function setAutosave(v) { autosave = v; }
  449. function save() {
  450. WBFileIO.save(function (ok) {
  451. if (ok) {
  452. WBUI.toast("Saved", "ok");
  453. updateSaveState();
  454. WBSettings.render();
  455. }
  456. });
  457. }
  458. function saveAs() {
  459. WBFileIO.saveAs(function (ok) {
  460. if (ok) {
  461. WBUI.toast("Saved as " + WBFileIO.fileName(), "ok");
  462. updateSaveState();
  463. WBSettings.render();
  464. }
  465. });
  466. }
  467. function openSite() {
  468. confirmDiscard(function () {
  469. WBFileIO.openDialog();
  470. /* openDialog resolves asynchronously through openPath */
  471. var poll = setInterval(function () {
  472. if (WBModel.get() && !WBModel.isDirty() && WBFileIO.currentPath()) {
  473. clearInterval(poll);
  474. afterProjectLoaded();
  475. }
  476. }, 250);
  477. setTimeout(function () { clearInterval(poll); }, 60000);
  478. });
  479. }
  480. /*
  481. New Site opens the template gallery rather than dropping the user
  482. straight into the default starter page: a template arrives with every
  483. page written and its navigation already linked up.
  484. */
  485. function newSite() {
  486. confirmDiscard(function () {
  487. WBGallery.open("My Website").then(function (choice) {
  488. if (!choice) { return; }
  489. var tpl = choice.templateId ? WBTemplates.get(choice.templateId) : null;
  490. try {
  491. if (tpl) {
  492. WBModel.loadProject(WBTemplates.buildProject(tpl, choice.name));
  493. } else {
  494. WBModel.newProject(choice.name, { blank: true });
  495. }
  496. } catch (e) {
  497. console.error("[wb] could not build the template", e);
  498. WBUI.toast("That template could not be loaded", "err");
  499. return;
  500. }
  501. WBFileIO.setPath("");
  502. afterProjectLoaded();
  503. showPanel("pages");
  504. openDock();
  505. WBUI.toast(tpl ? "Created from the " + tpl.name + " template" : "Blank site created", "ok");
  506. });
  507. });
  508. }
  509. function renameSite() {
  510. WBUI.prompt("Rename Site", "Site name", WBModel.get().name).then(function (name) {
  511. if (!name) { return; }
  512. WBModel.get().name = name;
  513. WBModel.commit("Rename site");
  514. refreshTitles();
  515. WBSettings.render();
  516. });
  517. }
  518. function confirmDiscard(next) {
  519. if (!WBModel.isDirty()) { next(); return; }
  520. WBUI.modal({
  521. title: "Unsaved Changes",
  522. body: WBUI.el("div", { text: "This site has changes that have not been saved to a file yet." }),
  523. buttons: [
  524. { label: "Cancel", value: null },
  525. { label: "Discard", value: "discard", danger: true },
  526. { label: "Save First", value: "save", primary: true }
  527. ]
  528. }).then(function (v) {
  529. if (v === "discard") { next(); }
  530. else if (v === "save") { WBFileIO.save(function (ok) { if (ok) { next(); } }); }
  531. });
  532. }
  533. /* ------------------------------------------------------ text tools -- */
  534. function bindTextToolbar() {
  535. var bar = document.getElementById("wb-text-toolbar");
  536. bar.querySelector("[data-tt='edit']").addEventListener("click", function () {
  537. var id = WBCanvas.getSelection();
  538. if (id) { WBCanvas.startTextEdit(id); }
  539. });
  540. ["left", "center", "right"].forEach(function (a) {
  541. bar.querySelector("[data-tt='align-" + a + "']").addEventListener("click", function () {
  542. var id = WBCanvas.getSelection();
  543. if (!id) { return; }
  544. WBModel.setStyle(id, "textAlign", a, WBCanvas.getDevice());
  545. WBModel.commit("Align text");
  546. WBCanvas.refreshStyles();
  547. WBInspector.render();
  548. updateTextToolbarState();
  549. });
  550. });
  551. bar.querySelector("[data-tt='bold']").addEventListener("click", function () {
  552. requireEditing(function () { WBCanvas.execTextCommand("bold"); updateTextToolbarState(); });
  553. });
  554. bar.querySelector("[data-tt='italic']").addEventListener("click", function () {
  555. requireEditing(function () { WBCanvas.execTextCommand("italic"); updateTextToolbarState(); });
  556. });
  557. bar.querySelector("[data-tt='link']").addEventListener("click", function () {
  558. requireEditing(function () {
  559. WBUI.prompt("Insert Link", "Link address", "", "https:// or about.html").then(function (v) {
  560. if (!v) { return; }
  561. WBCanvas.execTextCommand("createLink", v);
  562. });
  563. });
  564. });
  565. bar.querySelector("[data-tt='more']").addEventListener("click", function (e) {
  566. var id = WBCanvas.getSelection();
  567. var node = id ? WBModel.findNode(id) : null;
  568. var items = [
  569. { label: "Underline", icon: "underline", action: function () {
  570. requireEditing(function () { WBCanvas.execTextCommand("underline"); });
  571. } },
  572. { label: "Remove Link", icon: "unlink", action: function () {
  573. requireEditing(function () { WBCanvas.execTextCommand("unlink"); });
  574. } },
  575. { label: "Clear Formatting", icon: "close", action: function () {
  576. requireEditing(function () { WBCanvas.execTextCommand("removeFormat"); });
  577. } },
  578. { separator: true }
  579. ];
  580. if (node && node.type === "heading") {
  581. items.push({ header: "Heading level" });
  582. ["h1", "h2", "h3", "h4", "h5", "h6"].forEach(function (h) {
  583. items.push({
  584. label: h.toUpperCase(),
  585. checked: node.tag === h,
  586. action: function () {
  587. WBModel.setTag(node.id, h);
  588. WBModel.commit("Change heading level");
  589. rerenderCanvas();
  590. WBInspector.render();
  591. }
  592. });
  593. });
  594. } else {
  595. items.push({ label: "Open in inspector", icon: "gear", action: function () {
  596. WBInspector.render();
  597. } });
  598. }
  599. WBUI.menu(e.currentTarget, items, { alignRight: true });
  600. });
  601. }
  602. function requireEditing(fn) {
  603. if (!WBCanvas.isEditingText()) {
  604. var id = WBCanvas.getSelection();
  605. if (!id) { return; }
  606. WBCanvas.startTextEdit(id);
  607. setTimeout(fn, 60);
  608. return;
  609. }
  610. fn();
  611. }
  612. function updateTextToolbarState() {
  613. var bar = document.getElementById("wb-text-toolbar");
  614. var id = WBCanvas.getSelection();
  615. var node = id ? WBModel.findNode(id) : null;
  616. if (!node) { return; }
  617. var align = WBModel.effectiveStyle(node, "textAlign", WBCanvas.getDevice()) || "left";
  618. ["left", "center", "right"].forEach(function (a) {
  619. bar.querySelector("[data-tt='align-" + a + "']").classList.toggle("active", align === a);
  620. });
  621. bar.querySelector("[data-tt='bold']").classList.toggle("active", WBCanvas.queryTextState("bold"));
  622. bar.querySelector("[data-tt='italic']").classList.toggle("active", WBCanvas.queryTextState("italic"));
  623. }
  624. /* ------------------------------------------------------- shortcuts -- */
  625. function bindShortcuts() {
  626. document.addEventListener("keydown", function (e) {
  627. var mod = e.ctrlKey || e.metaKey;
  628. var tag = (e.target && e.target.tagName) ? e.target.tagName.toLowerCase() : "";
  629. var typing = tag === "input" || tag === "textarea" || e.target.isContentEditable;
  630. if (mod && e.key.toLowerCase() === "s") { e.preventDefault(); save(); return; }
  631. if (mod && e.key.toLowerCase() === "o") { e.preventDefault(); openSite(); return; }
  632. if (mod && e.key === "0") { e.preventDefault(); WBCanvas.zoomToFit(); updateZoomLabel(); return; }
  633. if (mod && e.key.toLowerCase() === "z" && !e.shiftKey) { e.preventDefault(); undo(); return; }
  634. if (mod && (e.key.toLowerCase() === "y" || (e.shiftKey && e.key.toLowerCase() === "z"))) {
  635. e.preventDefault(); redo(); return;
  636. }
  637. if (typing && !WBCanvas.isEditingText()) { return; }
  638. if (mod && e.shiftKey && e.key.toLowerCase() === "v") {
  639. e.preventDefault();
  640. var sel = WBCanvas.getSelection();
  641. if (sel) { pasteStyles(sel); }
  642. return;
  643. }
  644. if (mod && e.key.toLowerCase() === "d") {
  645. e.preventDefault();
  646. var d = WBCanvas.getSelection();
  647. if (d) { duplicateNode(d); }
  648. return;
  649. }
  650. if (e.key === "Escape") {
  651. if (WBCanvas.isEditingText()) { WBCanvas.stopTextEdit(); }
  652. else if (WBPublish.isPreview()) { WBPublish.togglePreview(false); }
  653. else { selectNode(null); }
  654. return;
  655. }
  656. if ((e.key === "Delete" || e.key === "Backspace") && !WBCanvas.isEditingText()) {
  657. var id = WBCanvas.getSelection();
  658. if (id) { e.preventDefault(); deleteNode(id); }
  659. return;
  660. }
  661. if (e.key === "Enter" && !WBCanvas.isEditingText()) {
  662. var s2 = WBCanvas.getSelection();
  663. var n2 = s2 ? WBModel.findNode(s2) : null;
  664. if (n2 && wbIsTextEditable(n2.type)) { e.preventDefault(); WBCanvas.startTextEdit(s2); }
  665. return;
  666. }
  667. });
  668. window.addEventListener("beforeunload", function (e) {
  669. if (WBModel.isDirty()) {
  670. e.preventDefault();
  671. e.returnValue = "";
  672. return "";
  673. }
  674. });
  675. }
  676. function undo() {
  677. if (WBModel.undo()) { WBUI.toast("Undo"); }
  678. }
  679. function redo() {
  680. if (WBModel.redo()) { WBUI.toast("Redo"); }
  681. }
  682. /* ------------------------------------------------------------ help -- */
  683. function bindHelp() {
  684. var body = document.querySelector("#wb-panel-help .wb-panel-bd");
  685. var items = [
  686. ["Add elements", "Drag a card from the Add panel onto the canvas, or click it to drop it inside whatever is selected."],
  687. ["Edit text", "Double-click any text on the canvas, or press Enter with it selected. The floating bar handles bold, italic and links."],
  688. ["Layers", "The Layers panel is the element tree of this page. Drag rows to reorder or re-parent; drop on the middle of a container to move inside it."],
  689. ["Responsive design", "Switch to Tablet or Mobile in the top bar, then edit. Those changes only apply at that width and narrower."],
  690. ["Publish", "Publish writes a static site into a folder of its own inside your ArozOS Personal Site web root, then serves it at /www/&lt;user&gt;/&lt;folder&gt;/."],
  691. ["Project files", "Sites are saved as .wbsite files anywhere in your file system. Publishing is a separate step and never overwrites your project file."]
  692. ];
  693. items.forEach(function (it) {
  694. body.appendChild(WBUI.el("div", { class: "wb-help-item" }, [
  695. WBUI.el("h4", { text: it[0] }),
  696. WBUI.el("p", { html: it[1] })
  697. ]));
  698. });
  699. body.appendChild(WBUI.el("button", {
  700. class: "wb-btn wb-btn-block wb-btn-sm",
  701. style: "margin-top:14px",
  702. type: "button",
  703. html: WBIcon("help", 13) + "<span>Keyboard shortcuts</span>",
  704. onclick: showShortcuts
  705. }));
  706. }
  707. function showShortcuts() {
  708. var rows = [
  709. ["Ctrl + S", "Save project"],
  710. ["Ctrl + O", "Open project"],
  711. ["Ctrl + Z", "Undo"],
  712. ["Ctrl + Shift + Z", "Redo"],
  713. ["Ctrl + D", "Duplicate selection"],
  714. ["Ctrl + Shift + V", "Paste copied styles"],
  715. ["Ctrl + 0", "Zoom to fit"],
  716. ["Enter", "Edit the selected text"],
  717. ["Delete", "Delete selection"],
  718. ["Escape", "Stop editing / deselect / leave preview"]
  719. ];
  720. var list = WBUI.el("div");
  721. rows.forEach(function (r) {
  722. list.appendChild(WBUI.el("div", {
  723. style: "display:flex;gap:12px;padding:6px 0;border-bottom:1px solid var(--wb-border)"
  724. }, [
  725. WBUI.el("span", { class: "wb-kbd", text: r[0] }),
  726. WBUI.el("span", { text: r[1], style: "color:var(--wb-text-dim)" })
  727. ]));
  728. });
  729. WBUI.modal({ title: "Keyboard Shortcuts", body: list });
  730. }
  731. function showAbout() {
  732. WBUI.modal({
  733. title: "ArozOS Site Builder",
  734. body: WBUI.el("div", {
  735. html: "<p>A visual website builder for ArozOS. Sites are saved as <code>.wbsite</code> " +
  736. "project files and published as plain static HTML into your Personal Site web root " +
  737. "- no runtime, no database, nothing to keep running.</p>" +
  738. "<p style='margin-top:10px;color:var(--wb-text-dim)'>Part of the ArozOS web desktop. " +
  739. "Licensed under GPLv3.</p>"
  740. })
  741. });
  742. }
  743. /* ----------------------------------------------------------- theme -- */
  744. function applyTheme() {
  745. function setDark(dark) { document.body.classList.toggle("dark", !!dark); }
  746. try {
  747. if (typeof ao_module_getSystemThemeColor === "function") {
  748. ao_module_getSystemThemeColor(function (c) { setDark(c !== "whiteTheme"); });
  749. }
  750. } catch (e) { /* standalone - keep the light theme */ }
  751. window.desktopThemeChanged = function (theme) { setDark(theme === "dark" || theme === "darkTheme"); };
  752. try {
  753. if (typeof ao_module_onThemeChanged === "function") {
  754. ao_module_onThemeChanged(function (dark) { setDark(dark); });
  755. }
  756. } catch (e) { /* older ao_module - the global above still works */ }
  757. }
  758. function renderPreviewState(on) {
  759. document.getElementById("wb-preview-btn").classList.toggle("active", on);
  760. }
  761. return {
  762. init: init,
  763. showPanel: showPanel,
  764. insertElement: insertElement,
  765. deleteNode: deleteNode,
  766. duplicateNode: duplicateNode,
  767. wrapInContainer: wrapInContainer,
  768. unwrapNode: unwrapNode,
  769. copyStyles: copyStyles,
  770. pasteStyles: pasteStyles,
  771. selectNode: selectNode,
  772. highlightNode: highlightNode,
  773. rerenderCanvas: rerenderCanvas,
  774. refreshInspector: refreshInspector,
  775. refreshTitles: refreshTitles,
  776. switchPage: switchPage,
  777. save: save,
  778. saveAs: saveAs,
  779. getAutosave: getAutosave,
  780. setAutosave: setAutosave,
  781. renderPreviewState: renderPreviewState,
  782. updateSaveState: updateSaveState
  783. };
  784. })();
  785. document.addEventListener("DOMContentLoaded", function () { WBApp.init(); });