From 049a37aa0e7d37cafd979e7d470c7649700b5010 Mon Sep 17 00:00:00 2001 From: Andrew Dolgov Date: Sat, 1 Dec 2018 17:05:28 +0300 Subject: WIP reshuffling of JS global context into separate logical objects --- js/tt-rss.js | 609 ++++++++++++++++++++++------------------------------------- 1 file changed, 227 insertions(+), 382 deletions(-) (limited to 'js/tt-rss.js') diff --git a/js/tt-rss.js b/js/tt-rss.js index 99a484e9a..b5b785321 100644 --- a/js/tt-rss.js +++ b/js/tt-rss.js @@ -1,148 +1,215 @@ /* global dijit, __ */ -let global_unread = -1; let _widescreen_mode = false; -let _rpc_seq = 0; -let _active_feed_id = 0; -let _active_feed_is_cat = false; let hotkey_actions = {}; -let _headlines_scroll_timeout = false; -function next_seq() { - _rpc_seq += 1; - return _rpc_seq; -} +const App = { + _rpc_seq: 0, + global_unread: -1, + next_seq: function() { + this._rpc_seq += 1; + return this._rpc_seq; + }, + get_seq: function() { + return this._rpc_seq; + }, + updateTitle: function() { + let tmp = "Tiny Tiny RSS"; + + if (this.global_unread > 0) { + tmp = "(" + this.global_unread + ") " + tmp; + } -function get_seq() { - return _rpc_seq; -} + document.title = tmp; + }, + isCombinedMode: function() { + return getInitParam("combined_display_mode"); + }, + hotkeyHandler(event) { + if (event.target.nodeName == "INPUT" || event.target.nodeName == "TEXTAREA") return; -function activeFeedIsCat() { - return !!_active_feed_is_cat; -} + const action_name = keyeventToAction(event); -function getActiveFeedId() { - return _active_feed_id; -} + if (action_name) { + const action_func = hotkey_actions[action_name]; -function setActiveFeedId(id, is_cat) { - hash_set('f', id); - hash_set('c', is_cat ? 1 : 0); + if (action_func != null) { + action_func(); + event.stopPropagation(); + return false; + } + } + }, + switchPanelMode: function(wide) { + if (App.isCombinedMode()) return; - _active_feed_id = id; - _active_feed_is_cat = is_cat; + const article_id = getActiveArticleId(); - $("headlines-frame").setAttribute("feed-id", id); - $("headlines-frame").setAttribute("is-cat", is_cat ? 1 : 0); + if (wide) { + dijit.byId("headlines-wrap-inner").attr("design", 'sidebar'); + dijit.byId("content-insert").attr("region", "trailing"); - selectFeed(id, is_cat); + dijit.byId("content-insert").domNode.setStyle({width: '50%', + height: 'auto', + borderTopWidth: '0px' }); - PluginHost.run(PluginHost.HOOK_FEED_SET_ACTIVE, _active_article_id); -} + if (parseInt(getCookie("ttrss_ci_width")) > 0) { + dijit.byId("content-insert").domNode.setStyle( + {width: getCookie("ttrss_ci_width") + "px" }); + } + + $("headlines-frame").setStyle({ borderBottomWidth: '0px' }); + $("headlines-frame").addClassName("wide"); + } else { + + dijit.byId("content-insert").attr("region", "bottom"); + + dijit.byId("content-insert").domNode.setStyle({width: 'auto', + height: '50%', + borderTopWidth: '0px'}); -function updateFeedList() { - try { - Element.show("feedlistLoading"); + if (parseInt(getCookie("ttrss_ci_height")) > 0) { + dijit.byId("content-insert").domNode.setStyle( + {height: getCookie("ttrss_ci_height") + "px" }); + } - resetCounterCache(); + $("headlines-frame").setStyle({ borderBottomWidth: '1px' }); + $("headlines-frame").removeClassName("wide"); - if (dijit.byId("feedTree")) { - dijit.byId("feedTree").destroyRecursive(); } - const store = new dojo.data.ItemFileWriteStore({ - url: "backend.php?op=pref_feeds&method=getfeedtree&mode=2" - }); + Article.closeArticlePanel(); - const treeModel = new fox.FeedStoreModel({ - store: store, - query: { - "type": getInitParam('enable_feed_cats') == 1 ? "category" : "feed" - }, - rootId: "root", - rootLabel: "Feeds", - childrenAttrs: ["items"] - }); + if (article_id) view(article_id); - const tree = new fox.FeedTree({ - model: treeModel, - onClick: function (item, node) { - const id = String(item.id); - const is_cat = id.match("^CAT:"); - const feed = id.substr(id.indexOf(":") + 1); - viewfeed({feed: feed, is_cat: is_cat}); - return false; - }, - openOnClick: false, - showRoot: false, - persist: true, - id: "feedTree", - }, "feedTree"); - - var tmph = dojo.connect(dijit.byId('feedMenu'), '_openMyself', function (event) { - console.log(dijit.getEnclosingWidget(event.target)); - dojo.disconnect(tmph); - }); + xhrPost("backend.php", {op: "rpc", method: "setpanelmode", wide: wide ? 1 : 0}); + }, + parseRuntimeInfo: function(data) { - $("feeds-holder").appendChild(tree.domNode); + //console.log("parsing runtime info..."); - var tmph = dojo.connect(tree, 'onLoad', function () { - dojo.disconnect(tmph); - Element.hide("feedlistLoading"); + for (const k in data) { + const v = data[k]; - try { - feedlist_init(); + if (k == "dep_ts" && parseInt(getInitParam("dep_ts")) > 0) { + if (parseInt(getInitParam("dep_ts")) < parseInt(v) && getInitParam("reload_on_ts_change")) { + window.location.reload(); + } + } - setLoadingProgress(25); - } catch (e) { - exception_error(e); + if (k == "daemon_is_running" && v != 1) { + notify_error("Update daemon is not running.", true); + return; } - }); - tree.startup(); - } catch (e) { - exception_error(e); - } -} + if (k == "update_result") { + const updatesIcon = dijit.byId("updatesIcon").domNode; -function catchupAllFeeds() { + if (v) { + Element.show(updatesIcon); + } else { + Element.hide(updatesIcon); + } + } - const str = __("Mark all articles as read?"); + if (k == "daemon_stamp_ok" && v != 1) { + notify_error("Update daemon is not updating feeds.", true); + return; + } - if (getInitParam("confirm_feed_catchup") != 1 || confirm(str)) { + if (k == "max_feed_id" || k == "num_feeds") { + if (init_params[k] != v) { + console.log("feed count changed, need to reload feedlist."); + Feeds.reload(); + } + } - notify_progress("Marking all feeds as read..."); + init_params[k] = v; + notify(''); + } - xhrPost("backend.php", {op: "feeds", method: "catchupAll"}, () => { - request_counters(true); - viewCurrentFeed(); - }); + PluginHost.run(PluginHost.HOOK_RUNTIME_INFO_LOADED, data); + }, + handleRpcJson: function(transport) { - global_unread = 0; - updateTitle(""); - } -} + const netalert_dijit = dijit.byId("net-alert"); + let netalert = false; -function viewCurrentFeed(method) { - console.log("viewCurrentFeed: " + method); + if (netalert_dijit) netalert = netalert_dijit.domNode; - if (getActiveFeedId() != undefined) { - viewfeed({feed: getActiveFeedId(), is_cat: activeFeedIsCat(), method: method}); - } - return false; // block unneeded form submits -} + try { + const reply = JSON.parse(transport.responseText); -function timeout() { - if (getInitParam("bw_limit") != "1") { - request_counters(true); - setTimeout(timeout, 60*1000); - } -} + if (reply) { + + const error = reply['error']; + + if (error) { + const code = error['code']; + const msg = error['msg']; + + console.warn("[handleRpcJson] received fatal error " + code + "/" + msg); + + if (code != 0) { + fatalError(code, msg); + return false; + } + } + + const seq = reply['seq']; + + if (seq && this.get_seq() != seq) { + console.log("[handleRpcJson] sequence mismatch: " + seq + + " (want: " + this.get_seq() + ")"); + return true; + } + + const message = reply['message']; + + if (message == "UPDATE_COUNTERS") { + console.log("need to refresh counters..."); + setInitParam("last_article_id", -1); + Feeds.requestCounters(true); + } + + const counters = reply['counters']; + + if (counters) + Feeds.parseCounters(counters); + + const runtime_info = reply['runtime-info']; + + if (runtime_info) + this.parseRuntimeInfo(runtime_info); + + if (netalert) netalert.hide(); + + return reply; + + } else { + if (netalert) + netalert.show(); + else + notify_error("Communication problem with server."); + } + + } catch (e) { + if (netalert) + netalert.show(); + else + notify_error("Communication problem with server."); + + console.error(e); + } + + return false; + }, +}; function search() { const query = "backend.php?op=feeds&method=search¶m=" + - param_escape(getActiveFeedId() + ":" + activeFeedIsCat()); + param_escape(Feeds.getActiveFeedId() + ":" + Feeds.activeFeedIsCat()); if (dijit.byId("searchDlg")) dijit.byId("searchDlg").destroyRecursive(); @@ -153,9 +220,9 @@ function search() { style: "width: 600px", execute: function() { if (this.validate()) { - _search_query = this.attr('value'); + Feeds._search_query = this.attr('value'); this.hide(); - viewCurrentFeed(); + Feeds.viewCurrentFeed(); } }, href: query}); @@ -163,16 +230,6 @@ function search() { dialog.show(); } -function updateTitle() { - let tmp = "Tiny Tiny RSS"; - - if (global_unread > 0) { - tmp = "(" + global_unread + ") " + tmp; - } - - document.title = tmp; -} - function genericSanityCheck() { setCookie("ttrss_test", "TEST"); @@ -272,15 +329,15 @@ function init() { function init_hotkey_actions() { hotkey_actions["next_feed"] = function() { const rv = dijit.byId("feedTree").getNextFeed( - getActiveFeedId(), activeFeedIsCat()); + Feeds.getActiveFeedId(), Feeds.activeFeedIsCat()); - if (rv) viewfeed({feed: rv[0], is_cat: rv[1], delayed: true}) + if (rv) Feeds.viewfeed({feed: rv[0], is_cat: rv[1], delayed: true}) }; hotkey_actions["prev_feed"] = function() { const rv = dijit.byId("feedTree").getPreviousFeed( - getActiveFeedId(), activeFeedIsCat()); + Feeds.getActiveFeedId(), Feeds.activeFeedIsCat()); - if (rv) viewfeed({feed: rv[0], is_cat: rv[1], delayed: true}) + if (rv) Feeds.viewfeed({feed: rv[0], is_cat: rv[1], delayed: true}) }; hotkey_actions["next_article"] = function() { moveToPost('next'); @@ -320,7 +377,7 @@ function init_hotkey_actions() { } hotkey_actions["open_in_new_window"] = function() { if (getActiveArticleId()) { - openArticleInNewWindow(getActiveArticleId()); + Article.openArticleInNewWindow(getActiveArticleId()); } }; hotkey_actions["catchup_below"] = function() { @@ -336,10 +393,10 @@ function init_hotkey_actions() { scrollArticle(-40); }; hotkey_actions["close_article"] = function() { - if (isCombinedMode()) { + if (App.isCombinedMode()) { cdmCollapseActive(); } else { - closeArticlePanel(); + Article.closeArticlePanel(); } }; hotkey_actions["email_article"] = function() { @@ -370,20 +427,20 @@ function init_hotkey_actions() { selectArticles('none'); }; hotkey_actions["feed_refresh"] = function() { - if (getActiveFeedId() != undefined) { - viewfeed({feed: getActiveFeedId(), is_cat: activeFeedIsCat()}); + if (Feeds.getActiveFeedId() != undefined) { + Feeds.viewfeed({feed: Feeds.getActiveFeedId(), is_cat: Feeds.activeFeedIsCat()}); return; } }; hotkey_actions["feed_unhide_read"] = function() { - toggleDispRead(); + Feeds.toggleDispRead(); }; hotkey_actions["feed_subscribe"] = function() { quickAddFeed(); }; hotkey_actions["feed_debug_update"] = function() { - if (!activeFeedIsCat() && parseInt(getActiveFeedId()) > 0) { - window.open("backend.php?op=feeds&method=update_debugger&feed_id=" + getActiveFeedId() + + if (!Feeds.activeFeedIsCat() && parseInt(Feeds.getActiveFeedId()) > 0) { + window.open("backend.php?op=feeds&method=update_debugger&feed_id=" + Feeds.getActiveFeedId() + "&csrf_token=" + getInitParam("csrf_token")); } else { alert("You can't debug this kind of feed."); @@ -391,17 +448,17 @@ function init_hotkey_actions() { }; hotkey_actions["feed_debug_viewfeed"] = function() { - viewfeed({feed: getActiveFeedId(), is_cat: activeFeedIsCat(), viewfeed_debug: true}); + Feeds.viewfeed({feed: Feeds.getActiveFeedId(), is_cat: Feeds.activeFeedIsCat(), viewfeed_debug: true}); }; hotkey_actions["feed_edit"] = function() { - if (activeFeedIsCat()) + if (Feeds.activeFeedIsCat()) alert(__("You can't edit this kind of feed.")); else - editFeed(getActiveFeedId()); + editFeed(Feeds.getActiveFeedId()); }; hotkey_actions["feed_catchup"] = function() { - if (getActiveFeedId() != undefined) { + if (Feeds.getActiveFeedId() != undefined) { catchupCurrentFeed(); return; } @@ -411,32 +468,32 @@ function init_hotkey_actions() { }; hotkey_actions["feed_toggle_vgroup"] = function() { xhrPost("backend.php", {op: "rpc", method: "togglepref", key: "VFEED_GROUP_BY_FEED"}, () => { - viewCurrentFeed(); + Feeds.viewCurrentFeed(); }) }; hotkey_actions["catchup_all"] = function() { - catchupAllFeeds(); + Feeds.catchupAllFeeds(); }; hotkey_actions["cat_toggle_collapse"] = function() { - if (activeFeedIsCat()) { - dijit.byId("feedTree").collapseCat(getActiveFeedId()); + if (Feeds.activeFeedIsCat()) { + dijit.byId("feedTree").collapseCat(Feeds.getActiveFeedId()); return; } }; hotkey_actions["goto_all"] = function() { - viewfeed({feed: -4}); + Feeds.viewfeed({feed: -4}); }; hotkey_actions["goto_fresh"] = function() { - viewfeed({feed: -3}); + Feeds.viewfeed({feed: -3}); }; hotkey_actions["goto_marked"] = function() { - viewfeed({feed: -1}); + Feeds.viewfeed({feed: -1}); }; hotkey_actions["goto_published"] = function() { - viewfeed({feed: -2}); + Feeds.viewfeed({feed: -2}); }; hotkey_actions["goto_tagcloud"] = function() { - displayDlg(__("Tag cloud"), "printTagCloud"); + Utils.displayDlg(__("Tag cloud"), "printTagCloud"); }; hotkey_actions["goto_prefs"] = function() { gotoPreferences(); @@ -467,7 +524,7 @@ function init_hotkey_actions() { quickAddFilter(); }; hotkey_actions["collapse_sidebar"] = function() { - collapse_feedlist(); + Feeds.viewCurrentFeed(); }; hotkey_actions["toggle_embed_original"] = function() { if (typeof embedOriginalArticle != "undefined") { @@ -478,32 +535,32 @@ function init_hotkey_actions() { } }; hotkey_actions["toggle_widescreen"] = function() { - if (!isCombinedMode()) { + if (!App.isCombinedMode()) { _widescreen_mode = !_widescreen_mode; // reset stored sizes because geometry changed setCookie("ttrss_ci_width", 0); setCookie("ttrss_ci_height", 0); - switchPanelMode(_widescreen_mode); + App.switchPanelMode(_widescreen_mode); } else { alert(__("Widescreen is not available in combined mode.")); } }; hotkey_actions["help_dialog"] = function() { - helpDialog("main"); + Utils.helpDialog("main"); }; hotkey_actions["toggle_combined_mode"] = function() { notify_progress("Loading, please wait..."); - const value = isCombinedMode() ? "false" : "true"; + const value = App.isCombinedMode() ? "false" : "true"; xhrPost("backend.php", {op: "rpc", method: "setpref", key: "COMBINED_DISPLAY_MODE", value: value}, () => { setInitParam("combined_display_mode", !getInitParam("combined_display_mode")); - closeArticlePanel(); - viewCurrentFeed(); + Article.closeArticlePanel(); + Feeds.viewCurrentFeed(); }) }; hotkey_actions["toggle_cdm_expanded"] = function() { @@ -513,15 +570,15 @@ function init_hotkey_actions() { xhrPost("backend.php", { op: "rpc", method: "setpref", key: "CDM_EXPANDED", value: value }, () => { setInitParam("cdm_expanded", !getInitParam("cdm_expanded")); - viewCurrentFeed(); + Feeds.viewCurrentFeed(); }); }; } function init_second_stage() { - updateFeedList(); - closeArticlePanel(); + Feeds.reload(); + Article.closeArticlePanel(); if (parseInt(getCookie("ttrss_fh_width")) > 0) { dijit.byId("feeds-holder").domNode.setStyle( @@ -559,7 +616,7 @@ function init_second_stage() { const hash_feed_is_cat = hash_get('c') == "1"; if (hash_feed_id != undefined) { - setActiveFeedId(hash_feed_id, hash_feed_is_cat); + Feeds.setActiveFeedId(hash_feed_id, hash_feed_is_cat); } setLoadingProgress(50); @@ -569,15 +626,9 @@ function init_second_stage() { sessionStorage.clear(); _widescreen_mode = getInitParam("widescreen"); - switchPanelMode(_widescreen_mode); - - $("headlines-frame").onscroll = (event) => { - clearTimeout(_headlines_scroll_timeout); - _headlines_scroll_timeout = window.setTimeout(function() { - //console.log('done scrolling', event); - headlinesScrollHandler(event); - }, 50); - } + App.switchPanelMode(_widescreen_mode); + + Headlines.initScrollHandler(); console.log("second stage ok"); @@ -596,7 +647,7 @@ function quickMenuGo(opid) { document.location.href = "backend.php?op=logout"; break; case "qmcTagCloud": - displayDlg(__("Tag cloud"), "printTagCloud"); + Utils.displayDlg(__("Tag cloud"), "printTagCloud"); break; case "qmcSearch": search(); @@ -608,15 +659,15 @@ function quickMenuGo(opid) { window.location.href = "backend.php?op=digest"; break; case "qmcEditFeed": - if (activeFeedIsCat()) + if (Feeds.activeFeedIsCat()) alert(__("You can't edit this kind of feed.")); else - editFeed(getActiveFeedId()); + editFeed(Feeds.getActiveFeedId()); break; case "qmcRemoveFeed": - var actid = getActiveFeedId(); + var actid = Feeds.getActiveFeedId(); - if (activeFeedIsCat()) { + if (Feeds.activeFeedIsCat()) { alert(__("You can't unsubscribe from the category.")); return; } @@ -635,120 +686,35 @@ function quickMenuGo(opid) { } break; case "qmcCatchupAll": - catchupAllFeeds(); + Feeds.catchupAllFeeds(); break; case "qmcShowOnlyUnread": - toggleDispRead(); + Feeds.toggleDispRead(); break; case "qmcToggleWidescreen": - if (!isCombinedMode()) { + if (!App.isCombinedMode()) { _widescreen_mode = !_widescreen_mode; // reset stored sizes because geometry changed setCookie("ttrss_ci_width", 0); setCookie("ttrss_ci_height", 0); - switchPanelMode(_widescreen_mode); + App.switchPanelMode(_widescreen_mode); } else { alert(__("Widescreen is not available in combined mode.")); } break; case "qmcHKhelp": - helpDialog("main"); + Utils.helpDialog("main"); break; default: console.log("quickMenuGo: unknown action: " + opid); } } -function toggleDispRead() { - - const hide = !(getInitParam("hide_read_feeds") == "1"); - - xhrPost("backend.php", {op: "rpc", method: "setpref", key: "HIDE_READ_FEEDS", value: hide}, () => { - hideOrShowFeeds(hide); - setInitParam("hide_read_feeds", hide); - }); -} - -function parse_runtime_info(data) { - - //console.log("parsing runtime info..."); - - for (const k in data) { - const v = data[k]; - -// console.log("RI: " + k + " => " + v); - - if (k == "dep_ts" && parseInt(getInitParam("dep_ts")) > 0) { - if (parseInt(getInitParam("dep_ts")) < parseInt(v) && getInitParam("reload_on_ts_change")) { - window.location.reload(); - } - } - - if (k == "daemon_is_running" && v != 1) { - notify_error("Update daemon is not running.", true); - return; - } - - if (k == "update_result") { - const updatesIcon = dijit.byId("updatesIcon").domNode; - - if (v) { - Element.show(updatesIcon); - } else { - Element.hide(updatesIcon); - } - } - - if (k == "daemon_stamp_ok" && v != 1) { - notify_error("Update daemon is not updating feeds.", true); - return; - } - - if (k == "max_feed_id" || k == "num_feeds") { - if (init_params[k] != v) { - console.log("feed count changed, need to reload feedlist."); - updateFeedList(); - } - } - - init_params[k] = v; - notify(''); - } - - PluginHost.run(PluginHost.HOOK_RUNTIME_INFO_LOADED, data); -} - -function collapse_feedlist() { - Element.toggle("feeds-holder"); - - const splitter = $("feeds-holder_splitter"); - - Element.visible("feeds-holder") ? splitter.show() : splitter.hide(); - - dijit.byId("main").resize(); -} - function viewModeChanged() { cache_clear(); - return viewCurrentFeed(''); -} - -function hotkey_handler(e) { - if (e.target.nodeName == "INPUT" || e.target.nodeName == "TEXTAREA") return; - - const action_name = keyeventToAction(e); - - if (action_name) { - const action_func = hotkey_actions[action_name]; - - if (action_func != null) { - action_func(); - e.stopPropagation(); - return false; - } - } + return Feeds.viewCurrentFeed(''); } function inPreferences() { @@ -769,136 +735,15 @@ function reverseHeadlineOrder() { order_by.attr('value', value); - viewCurrentFeed(); - -} - -function handle_rpc_json(transport, scheduled_call) { - - const netalert_dijit = dijit.byId("net-alert"); - let netalert = false; - - if (netalert_dijit) netalert = netalert_dijit.domNode; - - try { - const reply = JSON.parse(transport.responseText); - - if (reply) { - - const error = reply['error']; - - if (error) { - const code = error['code']; - const msg = error['msg']; - - console.warn("[handle_rpc_json] received fatal error " + code + "/" + msg); - - if (code != 0) { - fatalError(code, msg); - return false; - } - } - - const seq = reply['seq']; - - if (seq && get_seq() != seq) { - console.log("[handle_rpc_json] sequence mismatch: " + seq + - " (want: " + get_seq() + ")"); - return true; - } - - const message = reply['message']; - - if (message == "UPDATE_COUNTERS") { - console.log("need to refresh counters..."); - setInitParam("last_article_id", -1); - request_counters(true); - } - - const counters = reply['counters']; - - if (counters) - parse_counters(counters, scheduled_call); - - const runtime_info = reply['runtime-info']; - - if (runtime_info) - parse_runtime_info(runtime_info); - - if (netalert) netalert.hide(); - - return reply; - - } else { - if (netalert) - netalert.show(); - else - notify_error("Communication problem with server."); - } - - } catch (e) { - if (netalert) - netalert.show(); - else - notify_error("Communication problem with server."); - - console.error(e); - } - - return false; -} - -function switchPanelMode(wide) { - if (isCombinedMode()) return; - - const article_id = getActiveArticleId(); - - if (wide) { - dijit.byId("headlines-wrap-inner").attr("design", 'sidebar'); - dijit.byId("content-insert").attr("region", "trailing"); - - dijit.byId("content-insert").domNode.setStyle({width: '50%', - height: 'auto', - borderTopWidth: '0px' }); - - if (parseInt(getCookie("ttrss_ci_width")) > 0) { - dijit.byId("content-insert").domNode.setStyle( - {width: getCookie("ttrss_ci_width") + "px" }); - } - - $("headlines-frame").setStyle({ borderBottomWidth: '0px' }); - $("headlines-frame").addClassName("wide"); - - } else { - - dijit.byId("content-insert").attr("region", "bottom"); - - dijit.byId("content-insert").domNode.setStyle({width: 'auto', - height: '50%', - borderTopWidth: '0px'}); - - if (parseInt(getCookie("ttrss_ci_height")) > 0) { - dijit.byId("content-insert").domNode.setStyle( - {height: getCookie("ttrss_ci_height") + "px" }); - } - - $("headlines-frame").setStyle({ borderBottomWidth: '1px' }); - $("headlines-frame").removeClassName("wide"); - - } - - closeArticlePanel(); - - if (article_id) view(article_id); + Feeds.viewCurrentFeed(); - xhrPost("backend.php", {op: "rpc", method: "setpanelmode", wide: wide ? 1 : 0}); } function update_random_feed() { console.log("in update_random_feed"); xhrPost("backend.php", { op: "rpc", method: "updateRandomFeed" }, (transport) => { - handle_rpc_json(transport, true); + App.handleRpcJson(transport, true); window.setTimeout(update_random_feed, 30*1000); }); } -- cgit v1.2.3-54-g00ecf From d86ddbc635376231ba2e0a70c04f526cb9fedd58 Mon Sep 17 00:00:00 2001 From: Andrew Dolgov Date: Sat, 1 Dec 2018 17:21:26 +0300 Subject: further objectification of JS code --- classes/feeds.php | 4 +- index.php | 8 +- js/FeedTree.js | 4 +- js/feedlist.js | 330 ++++++++++++++++++++++++++---------------------------- js/functions.js | 128 +++++++++++++++++++++ js/tt-rss.js | 134 +--------------------- js/viewfeed.js | 38 +++---- 7 files changed, 316 insertions(+), 330 deletions(-) (limited to 'js/tt-rss.js') diff --git a/classes/feeds.php b/classes/feeds.php index 93e44e3bb..63366fd0d 100755 --- a/classes/feeds.php +++ b/classes/feeds.php @@ -388,7 +388,7 @@ class Feeds extends Handler_Protected { $vgroup_last_feed = $feed_id; - $vf_catchup_link = "".__('mark feed as read').""; + $vf_catchup_link = "".__('mark feed as read').""; $reply['content'] .= "
". "
$feed_icon_img
". @@ -481,7 +481,7 @@ class Feeds extends Handler_Protected { $vgroup_last_feed = $feed_id; - $vf_catchup_link = "".__('mark feed as read').""; + $vf_catchup_link = "".__('mark feed as read').""; $feed_icon_src = Feeds::getFeedIcon($feed_id); $feed_icon_img = ""; diff --git a/index.php b/index.php index 48bd559f8..820db9073 100644 --- a/index.php +++ b/index.php @@ -207,16 +207,16 @@ -
+
-
+
-
+
-
+
diff --git a/js/FeedTree.js b/js/FeedTree.js index 21a19bf85..55eb3dc30 100755 --- a/js/FeedTree.js +++ b/js/FeedTree.js @@ -41,7 +41,7 @@ define(["dojo/_base/declare", "dojo/dom-construct", "dijit/Tree", "dijit/Menu"], menu.addChild(new dijit.MenuItem({ label: __("Mark as read"), onClick: function() { - catchupFeed(this.getParent().row_id); + Feeds.catchupFeed(this.getParent().row_id); }})); if (bare_id > 0) { @@ -69,7 +69,7 @@ define(["dojo/_base/declare", "dojo/dom-construct", "dijit/Tree", "dijit/Menu"], menu.addChild(new dijit.MenuItem({ label: __("Mark as read"), onClick: function() { - catchupFeed(this.getParent().row_id, true); + Feeds.catchupFeed(this.getParent().row_id, true); }})); menu.addChild(new dijit.MenuItem({ diff --git a/js/feedlist.js b/js/feedlist.js index b808451b4..c2a0e816d 100644 --- a/js/feedlist.js +++ b/js/feedlist.js @@ -69,23 +69,23 @@ const Feeds = { continue; } - /*if (getFeedUnread(id, (kind == "cat")) != ctr || + /*if (Feeds.getFeedUnread(id, (kind == "cat")) != ctr || (kind == "cat")) { }*/ - setFeedUnread(id, (kind == "cat"), ctr); - setFeedValue(id, (kind == "cat"), 'auxcounter', auxctr); + Feeds.setFeedUnread(id, (kind == "cat"), ctr); + Feeds.setFeedValue(id, (kind == "cat"), 'auxcounter', auxctr); if (kind != "cat") { - setFeedValue(id, false, 'error', error); - setFeedValue(id, false, 'updated', updated); + Feeds.setFeedValue(id, false, 'error', error); + Feeds.setFeedValue(id, false, 'updated', updated); if (id > 0) { if (has_img) { - setFeedIcon(id, false, + Feeds.setFeedIcon(id, false, getInitParam("icons_url") + "/" + id + ".ico?" + has_img); } else { - setFeedIcon(id, false, 'images/blank_icon.gif'); + Feeds.setFeedIcon(id, false, 'images/blank_icon.gif'); } } } @@ -104,7 +104,7 @@ const Feeds = { }, openNextUnreadFeed: function() { const is_cat = Feeds.activeFeedIsCat(); - const nuf = getNextUnreadFeed(Feeds.getActiveFeedId(), is_cat); + const nuf = Feeds.getNextUnreadFeed(Feeds.getActiveFeedId(), is_cat); if (nuf) this.viewfeed({feed: nuf, is_cat: is_cat}); }, collapseFeedlist: function() { @@ -129,13 +129,13 @@ const Feeds = { counters_last_request = timestamp; - let query = {op: "rpc", method: "getAllCounters", seq: App.next_seq()}; + let query = {op: "rpc", method: "getAllCounters", seq: Utils.next_seq()}; if (!force) query.last_article_id = getInitParam("last_article_id"); xhrPost("backend.php", query, (transport) => { - App.handleRpcJson(transport); + Utils.handleRpcJson(transport); }); } else { @@ -357,7 +357,7 @@ const Feeds = { Form.enable("main_toolbar_form"); if (!delayed) - if (!setFeedExpandoIcon(feed, is_cat, + if (!Feeds.setFeedExpandoIcon(feed, is_cat, (is_cat) ? 'images/indicator_tiny.gif' : 'images/indicator_white.gif')) notify_progress("Loading, please wait...", true); @@ -377,7 +377,7 @@ const Feeds = { catchupBatchedArticles(() => { xhrPost("backend.php", query, (transport) => { try { - setFeedExpandoIcon(feed, is_cat, 'images/blank_icon.gif'); + Feeds.setFeedExpandoIcon(feed, is_cat, 'images/blank_icon.gif'); Headlines.onLoaded(transport, offset); PluginHost.run(PluginHost.HOOK_FEED_LOADED, [feed, is_cat]); } catch (e) { @@ -404,221 +404,207 @@ const Feeds = { } }, decrementFeedCounter: function(feed, is_cat) { - let ctr = getFeedUnread(feed, is_cat); + let ctr = Feeds.getFeedUnread(feed, is_cat); if (ctr > 0) { - setFeedUnread(feed, is_cat, ctr - 1); + Feeds.setFeedUnread(feed, is_cat, ctr - 1); App.global_unread -= 1; App.updateTitle(); if (!is_cat) { - const cat = parseInt(getFeedCategory(feed)); + const cat = parseInt(Feeds.getFeedCategory(feed)); if (!isNaN(cat)) { - ctr = getFeedUnread(cat, true); + ctr = Feeds.getFeedUnread(cat, true); if (ctr > 0) { - setFeedUnread(cat, true, ctr - 1); + Feeds.setFeedUnread(cat, true, ctr - 1); } } } } - } -}; - -function getFeedUnread(feed, is_cat) { - try { - const tree = dijit.byId("feedTree"); - - if (tree && tree.model) - return tree.model.getFeedUnread(feed, is_cat); - - } catch (e) { - // - } - - return -1; -} - -function getFeedCategory(feed) { - try { - const tree = dijit.byId("feedTree"); - - if (tree && tree.model) - return tree.getFeedCategory(feed); - - } catch (e) { - // - } - - return false; -} - -function getFeedName(feed, is_cat) { - - if (isNaN(feed)) return feed; // it's a tag - - const tree = dijit.byId("feedTree"); - - if (tree && tree.model) - return tree.model.getFeedValue(feed, is_cat, 'name'); -} - -/* function getFeedValue(feed, is_cat, key) { - try { - const tree = dijit.byId("feedTree"); - - if (tree && tree.model) - return tree.model.getFeedValue(feed, is_cat, key); + }, + catchupFeed: function(feed, is_cat, mode) { + if (is_cat == undefined) is_cat = false; + + let str = false; + + switch (mode) { + case "1day": + str = __("Mark %w in %s older than 1 day as read?"); + break; + case "1week": + str = __("Mark %w in %s older than 1 week as read?"); + break; + case "2week": + str = __("Mark %w in %s older than 2 weeks as read?"); + break; + default: + str = __("Mark %w in %s as read?"); + } - } catch (e) { - // - } - return ''; -} */ + const mark_what = last_search_query && last_search_query[0] ? __("search results") : __("all articles"); + const fn = Feeds.getFeedName(feed, is_cat); -function setFeedUnread(feed, is_cat, unread) { - const tree = dijit.byId("feedTree"); + str = str.replace("%s", fn) + .replace("%w", mark_what); - if (tree && tree.model) - return tree.model.setFeedUnread(feed, is_cat, unread); -} + if (getInitParam("confirm_feed_catchup") == 1 && !confirm(str)) { + return; + } -function setFeedValue(feed, is_cat, key, value) { - try { - const tree = dijit.byId("feedTree"); + const catchup_query = { + op: 'rpc', method: 'catchupFeed', feed_id: feed, + is_cat: is_cat, mode: mode, search_query: last_search_query[0], + search_lang: last_search_query[1] + }; - if (tree && tree.model) - return tree.model.setFeedValue(feed, is_cat, key, value); + notify_progress("Loading, please wait...", true); - } catch (e) { - // - } -} + xhrPost("backend.php", catchup_query, (transport) => { + Utils.handleRpcJson(transport); -function setFeedIcon(feed, is_cat, src) { - const tree = dijit.byId("feedTree"); + const show_next_feed = getInitParam("on_catchup_show_next_feed") == "1"; - if (tree) return tree.setFeedIcon(feed, is_cat, src); -} + if (show_next_feed) { + const nuf = Feeds.getNextUnreadFeed(feed, is_cat); -function setFeedExpandoIcon(feed, is_cat, src) { - const tree = dijit.byId("feedTree"); + if (nuf) { + this.viewfeed({feed: nuf, is_cat: is_cat}); + } + } else if (feed == Feeds.getActiveFeedId() && is_cat == Feeds.activeFeedIsCat()) { + this.viewCurrentFeed(); + } - if (tree) return tree.setFeedExpandoIcon(feed, is_cat, src); + notify(""); + }); + }, + catchupCurrentFeed: function(mode) { + Feeds.catchupFeed(Feeds.getActiveFeedId(), Feeds.activeFeedIsCat(), mode); + }, + catchupFeedInGroup: function(id) { + const title = Feeds.getFeedName(id); - return false; -} + const str = __("Mark all articles in %s as read?").replace("%s", title); -function getNextUnreadFeed(feed, is_cat) { - const tree = dijit.byId("feedTree"); - const nuf = tree.model.getNextUnreadFeed(feed, is_cat); + if (getInitParam("confirm_feed_catchup") != 1 || confirm(str)) { - if (nuf) - return tree.model.store.getValue(nuf, 'bare_id'); -} + const rows = $$("#headlines-frame > div[id*=RROW][data-orig-feed-id='" + id + "']"); -function catchupCurrentFeed(mode) { - catchupFeed(Feeds.getActiveFeedId(), Feeds.activeFeedIsCat(), mode); -} + if (rows.length > 0) { -function catchupFeedInGroup(id) { - const title = getFeedName(id); + rows.each(function (row) { + row.removeClassName("Unread"); - const str = __("Mark all articles in %s as read?").replace("%s", title); + if (row.getAttribute("data-article-id") != getActiveArticleId()) { + new Effect.Fade(row, {duration: 0.5}); + } - if (getInitParam("confirm_feed_catchup") != 1 || confirm(str)) { + }); - const rows = $$("#headlines-frame > div[id*=RROW][data-orig-feed-id='"+id+"']"); + const feedTitles = $$("#headlines-frame > div[class='feed-title']"); - if (rows.length > 0) { + for (let i = 0; i < feedTitles.length; i++) { + if (feedTitles[i].getAttribute("data-feed-id") == id) { - rows.each(function (row) { - row.removeClassName("Unread"); + if (i < feedTitles.length - 1) { + new Effect.Fade(feedTitles[i], {duration: 0.5}); + } - if (row.getAttribute("data-article-id") != getActiveArticleId()) { - new Effect.Fade(row, {duration: 0.5}); + break; + } } - }); - - const feedTitles = $$("#headlines-frame > div[class='feed-title']"); + Headlines.updateFloatingTitle(true); + } - for (let i = 0; i < feedTitles.length; i++) { - if (feedTitles[i].getAttribute("data-feed-id") == id) { + notify_progress("Loading, please wait...", true); - if (i < feedTitles.length - 1) { - new Effect.Fade(feedTitles[i], {duration: 0.5}); - } + xhrPost("backend.php", {op: "rpc", method: "catchupFeed", feed_id: id, is_cat: false}, (transport) => { + Utils.handleRpcJson(transport); + }); + } + }, + getFeedUnread: function(feed, is_cat) { + try { + const tree = dijit.byId("feedTree"); - break; - } - } + if (tree && tree.model) + return tree.model.getFeedUnread(feed, is_cat); - Headlines.updateFloatingTitle(true); + } catch (e) { + // } - notify_progress("Loading, please wait...", true); + return -1; + }, + getFeedCategory: function(feed) { + try { + const tree = dijit.byId("feedTree"); - xhrPost("backend.php", { op: "rpc", method: "catchupFeed", feed_id: id, is_cat: false}, (transport) => { - App.handleRpcJson(transport); - }); - } -} - -function catchupFeed(feed, is_cat, mode) { - if (is_cat == undefined) is_cat = false; - - let str = false; - - switch (mode) { - case "1day": - str = __("Mark %w in %s older than 1 day as read?"); - break; - case "1week": - str = __("Mark %w in %s older than 1 week as read?"); - break; - case "2week": - str = __("Mark %w in %s older than 2 weeks as read?"); - break; - default: - str = __("Mark %w in %s as read?"); - } + if (tree && tree.model) + return tree.getFeedCategory(feed); - const mark_what = last_search_query && last_search_query[0] ? __("search results") : __("all articles"); - const fn = getFeedName(feed, is_cat); + } catch (e) { + // + } - str = str.replace("%s", fn) - .replace("%w", mark_what); + return false; + }, + getFeedName: function(feed, is_cat) { + if (isNaN(feed)) return feed; // it's a tag - if (getInitParam("confirm_feed_catchup") == 1 && !confirm(str)) { - return; - } + const tree = dijit.byId("feedTree"); - const catchup_query = {op: 'rpc', method: 'catchupFeed', feed_id: feed, - is_cat: is_cat, mode: mode, search_query: last_search_query[0], - search_lang: last_search_query[1]}; + if (tree && tree.model) + return tree.model.getFeedValue(feed, is_cat, 'name'); + }, + setFeedUnread: function(feed, is_cat, unread) { + const tree = dijit.byId("feedTree"); - notify_progress("Loading, please wait...", true); + if (tree && tree.model) + return tree.model.setFeedUnread(feed, is_cat, unread); + }, + setFeedValue: function(feed, is_cat, key, value) { + try { + const tree = dijit.byId("feedTree"); - xhrPost("backend.php", catchup_query, (transport) => { - App.handleRpcJson(transport); + if (tree && tree.model) + return tree.model.setFeedValue(feed, is_cat, key, value); - const show_next_feed = getInitParam("on_catchup_show_next_feed") == "1"; + } catch (e) { + // + } + }, + getFeedValue: function(feed, is_cat, key) { + try { + const tree = dijit.byId("feedTree"); - if (show_next_feed) { - const nuf = getNextUnreadFeed(feed, is_cat); + if (tree && tree.model) + return tree.model.getFeedValue(feed, is_cat, key); - if (nuf) { - Feeds.viewfeed({feed: nuf, is_cat: is_cat}); - } - } else if (feed == Feeds.getActiveFeedId() && is_cat == Feeds.activeFeedIsCat()) { - Feeds.viewCurrentFeed(); + } catch (e) { + // } + return ''; + }, + setFeedIcon: function(feed, is_cat, src) { + const tree = dijit.byId("feedTree"); - notify(""); - }); -} + if (tree) return tree.setFeedIcon(feed, is_cat, src); + }, + setFeedExpandoIcon: function(feed, is_cat, src) { + const tree = dijit.byId("feedTree"); + if (tree) return tree.setFeedExpandoIcon(feed, is_cat, src); + return false; + }, + getNextUnreadFeed: function(feed, is_cat) { + const tree = dijit.byId("feedTree"); + const nuf = tree.model.getNextUnreadFeed(feed, is_cat); + if (nuf) + return tree.model.store.getValue(nuf, 'bare_id'); + } +}; diff --git a/js/functions.js b/js/functions.js index d9778ad22..174dbebfe 100755 --- a/js/functions.js +++ b/js/functions.js @@ -57,6 +57,14 @@ Array.prototype.remove = function(s) { }; const Utils = { + _rpc_seq: 0, + next_seq: function() { + this._rpc_seq += 1; + return this._rpc_seq; + }, + get_seq: function() { + return this._rpc_seq; + }, cleanupMemory: function(root) { const dijits = dojo.query("[widgetid]", dijit.byId(root).domNode).map(dijit.byNode); @@ -127,6 +135,126 @@ const Utils = { return false; }, + handleRpcJson: function(transport) { + + const netalert_dijit = dijit.byId("net-alert"); + let netalert = false; + + if (netalert_dijit) netalert = netalert_dijit.domNode; + + try { + const reply = JSON.parse(transport.responseText); + + if (reply) { + + const error = reply['error']; + + if (error) { + const code = error['code']; + const msg = error['msg']; + + console.warn("[handleRpcJson] received fatal error " + code + "/" + msg); + + if (code != 0) { + fatalError(code, msg); + return false; + } + } + + const seq = reply['seq']; + + if (seq && this.get_seq() != seq) { + console.log("[handleRpcJson] sequence mismatch: " + seq + + " (want: " + this.get_seq() + ")"); + return true; + } + + const message = reply['message']; + + if (message == "UPDATE_COUNTERS") { + console.log("need to refresh counters..."); + setInitParam("last_article_id", -1); + Feeds.requestCounters(true); + } + + const counters = reply['counters']; + + if (counters) + Feeds.parseCounters(counters); + + const runtime_info = reply['runtime-info']; + + if (runtime_info) + Utils.parseRuntimeInfo(runtime_info); + + if (netalert) netalert.hide(); + + return reply; + + } else { + if (netalert) + netalert.show(); + else + notify_error("Communication problem with server."); + } + + } catch (e) { + if (netalert) + netalert.show(); + else + notify_error("Communication problem with server."); + + console.error(e); + } + + return false; + }, + parseRuntimeInfo: function(data) { + + //console.log("parsing runtime info..."); + + for (const k in data) { + const v = data[k]; + + if (k == "dep_ts" && parseInt(getInitParam("dep_ts")) > 0) { + if (parseInt(getInitParam("dep_ts")) < parseInt(v) && getInitParam("reload_on_ts_change")) { + window.location.reload(); + } + } + + if (k == "daemon_is_running" && v != 1) { + notify_error("Update daemon is not running.", true); + return; + } + + if (k == "update_result") { + const updatesIcon = dijit.byId("updatesIcon").domNode; + + if (v) { + Element.show(updatesIcon); + } else { + Element.hide(updatesIcon); + } + } + + if (k == "daemon_stamp_ok" && v != 1) { + notify_error("Update daemon is not updating feeds.", true); + return; + } + + if (k == "max_feed_id" || k == "num_feeds") { + if (init_params[k] != v) { + console.log("feed count changed, need to reload feedlist."); + Feeds.reload(); + } + } + + init_params[k] = v; + notify(''); + } + + PluginHost.run(PluginHost.HOOK_RUNTIME_INFO_LOADED, data); + }, }; function report_error(message, filename, lineno, colno, error) { diff --git a/js/tt-rss.js b/js/tt-rss.js index b5b785321..078ac7c63 100644 --- a/js/tt-rss.js +++ b/js/tt-rss.js @@ -4,15 +4,7 @@ let _widescreen_mode = false; let hotkey_actions = {}; const App = { - _rpc_seq: 0, global_unread: -1, - next_seq: function() { - this._rpc_seq += 1; - return this._rpc_seq; - }, - get_seq: function() { - return this._rpc_seq; - }, updateTitle: function() { let tmp = "Tiny Tiny RSS"; @@ -85,126 +77,6 @@ const App = { xhrPost("backend.php", {op: "rpc", method: "setpanelmode", wide: wide ? 1 : 0}); }, - parseRuntimeInfo: function(data) { - - //console.log("parsing runtime info..."); - - for (const k in data) { - const v = data[k]; - - if (k == "dep_ts" && parseInt(getInitParam("dep_ts")) > 0) { - if (parseInt(getInitParam("dep_ts")) < parseInt(v) && getInitParam("reload_on_ts_change")) { - window.location.reload(); - } - } - - if (k == "daemon_is_running" && v != 1) { - notify_error("Update daemon is not running.", true); - return; - } - - if (k == "update_result") { - const updatesIcon = dijit.byId("updatesIcon").domNode; - - if (v) { - Element.show(updatesIcon); - } else { - Element.hide(updatesIcon); - } - } - - if (k == "daemon_stamp_ok" && v != 1) { - notify_error("Update daemon is not updating feeds.", true); - return; - } - - if (k == "max_feed_id" || k == "num_feeds") { - if (init_params[k] != v) { - console.log("feed count changed, need to reload feedlist."); - Feeds.reload(); - } - } - - init_params[k] = v; - notify(''); - } - - PluginHost.run(PluginHost.HOOK_RUNTIME_INFO_LOADED, data); - }, - handleRpcJson: function(transport) { - - const netalert_dijit = dijit.byId("net-alert"); - let netalert = false; - - if (netalert_dijit) netalert = netalert_dijit.domNode; - - try { - const reply = JSON.parse(transport.responseText); - - if (reply) { - - const error = reply['error']; - - if (error) { - const code = error['code']; - const msg = error['msg']; - - console.warn("[handleRpcJson] received fatal error " + code + "/" + msg); - - if (code != 0) { - fatalError(code, msg); - return false; - } - } - - const seq = reply['seq']; - - if (seq && this.get_seq() != seq) { - console.log("[handleRpcJson] sequence mismatch: " + seq + - " (want: " + this.get_seq() + ")"); - return true; - } - - const message = reply['message']; - - if (message == "UPDATE_COUNTERS") { - console.log("need to refresh counters..."); - setInitParam("last_article_id", -1); - Feeds.requestCounters(true); - } - - const counters = reply['counters']; - - if (counters) - Feeds.parseCounters(counters); - - const runtime_info = reply['runtime-info']; - - if (runtime_info) - this.parseRuntimeInfo(runtime_info); - - if (netalert) netalert.hide(); - - return reply; - - } else { - if (netalert) - netalert.show(); - else - notify_error("Communication problem with server."); - } - - } catch (e) { - if (netalert) - netalert.show(); - else - notify_error("Communication problem with server."); - - console.error(e); - } - - return false; - }, }; function search() { @@ -459,7 +331,7 @@ function init_hotkey_actions() { }; hotkey_actions["feed_catchup"] = function() { if (Feeds.getActiveFeedId() != undefined) { - catchupCurrentFeed(); + Feeds.catchupCurrentFeed(); return; } }; @@ -677,7 +549,7 @@ function quickMenuGo(opid) { return; } - var fn = getFeedName(actid); + var fn = Feeds.getFeedName(actid); var pr = __("Unsubscribe from %s?").replace("%s", fn); @@ -743,7 +615,7 @@ function update_random_feed() { console.log("in update_random_feed"); xhrPost("backend.php", { op: "rpc", method: "updateRandomFeed" }, (transport) => { - App.handleRpcJson(transport, true); + Utils.handleRpcJson(transport, true); window.setTimeout(update_random_feed, 30*1000); }); } diff --git a/js/viewfeed.js b/js/viewfeed.js index 637aa0473..bb3f5ef98 100755 --- a/js/viewfeed.js +++ b/js/viewfeed.js @@ -75,7 +75,7 @@ const Headlines = { const view_mode = document.forms["main_toolbar_form"].view_mode.value; const unread_in_buffer = $$("#headlines-frame > div[id*=RROW][class*=Unread]").length; const num_all = $$("#headlines-frame > div[id*=RROW]").length; - const num_unread = getFeedUnread(Feeds.getActiveFeedId(), Feeds.activeFeedIsCat()); + const num_unread = Feeds.getFeedUnread(Feeds.getActiveFeedId(), Feeds.activeFeedIsCat()); // TODO implement marked & published @@ -248,7 +248,7 @@ const Headlines = { } }, onLoaded: function(transport, offset) { - const reply = App.handleRpcJson(transport); + const reply = Utils.handleRpcJson(transport); console.log("Headlines.onLoaded: offset=", offset); @@ -436,7 +436,7 @@ function view(id, noexpand) { xhrPost("backend.php", {op: "article", method: "view", id: id, cids: cids.toString()}, (transport) => { try { - const reply = App.handleRpcJson(transport); + const reply = Utils.handleRpcJson(transport); if (reply) { @@ -491,7 +491,7 @@ function toggleMark(id, client_only) { if (!client_only) xhrPost("backend.php", query, (transport) => { - App.handleRpcJson(transport); + Utils.handleRpcJson(transport); }); } } @@ -518,7 +518,7 @@ function togglePub(id, client_only) { if (!client_only) xhrPost("backend.php", query, (transport) => { - App.handleRpcJson(transport); + Utils.handleRpcJson(transport); }); } @@ -642,7 +642,7 @@ function toggleUnread(id, cmode) { if (row.className != origClassName) xhrPost("backend.php", {op: "rpc", method: "catchupSelected", cmode: cmode, ids: id},(transport) => { - App.handleRpcJson(transport); + Utils.handleRpcJson(transport); }); } } @@ -659,7 +659,7 @@ function selectionRemoveLabel(id, ids) { ids: ids.toString(), lid: id }; xhrPost("backend.php", query, (transport) => { - App.handleRpcJson(transport); + Utils.handleRpcJson(transport); updateHeadlineLabels(transport); }); } @@ -676,7 +676,7 @@ function selectionAssignLabel(id, ids) { ids: ids.toString(), lid: id }; xhrPost("backend.php", query, (transport) => { - App.handleRpcJson(transport); + Utils.handleRpcJson(transport); updateHeadlineLabels(transport); }); } @@ -719,7 +719,7 @@ function selectionToggleUnread(params) { notify_progress("Loading, please wait..."); xhrPost("backend.php", query, (transport) => { - App.handleRpcJson(transport); + Utils.handleRpcJson(transport); if (callback) callback(transport); }); } @@ -740,7 +740,7 @@ function selectionToggleMarked(ids) { ids: rows.toString(), cmode: 2 }; xhrPost("backend.php", query, (transport) => { - App.handleRpcJson(transport); + Utils.handleRpcJson(transport); }); } @@ -762,7 +762,7 @@ function selectionTogglePublished(ids) { ids: rows.toString(), cmode: 2 }; xhrPost("backend.php", query, (transport) => { - App.handleRpcJson(transport); + Utils.handleRpcJson(transport); }); } } @@ -862,7 +862,7 @@ function deleteSelection() { return; } - const fn = getFeedName(Feeds.getActiveFeedId(), Feeds.activeFeedIsCat()); + const fn = Feeds.getFeedName(Feeds.getActiveFeedId(), Feeds.activeFeedIsCat()); let str; if (Feeds.getActiveFeedId() != 0) { @@ -881,7 +881,7 @@ function deleteSelection() { const query = { op: "rpc", method: "delete", ids: rows.toString() }; xhrPost("backend.php", query, (transport) => { - App.handleRpcJson(transport); + Utils.handleRpcJson(transport); Feeds.viewCurrentFeed(); }); } @@ -896,7 +896,7 @@ function archiveSelection() { return; } - const fn = getFeedName(Feeds.getActiveFeedId(), Feeds.activeFeedIsCat()); + const fn = Feeds.getFeedName(Feeds.getActiveFeedId(), Feeds.activeFeedIsCat()); let str; let op; @@ -924,7 +924,7 @@ function archiveSelection() { const query = {op: "rpc", method: op, ids: rows.toString()}; xhrPost("backend.php", query, (transport) => { - App.handleRpcJson(transport); + Utils.handleRpcJson(transport); Feeds.viewCurrentFeed(); }); } @@ -938,7 +938,7 @@ function catchupSelection() { return; } - const fn = getFeedName(Feeds.getActiveFeedId(), Feeds.activeFeedIsCat()); + const fn = Feeds.getFeedName(Feeds.getActiveFeedId(), Feeds.activeFeedIsCat()); let str = ngettext("Mark %d selected article in %s as read?", "Mark %d selected articles in %s as read?", rows.length); @@ -1091,7 +1091,7 @@ function catchupBatchedArticles(callback) { cmode: 0, ids: batch.toString() }; xhrPost("backend.php", query, (transport) => { - const reply = App.handleRpcJson(transport); + const reply = Utils.handleRpcJson(transport); if (reply) { const batch = reply.ids; @@ -1167,7 +1167,7 @@ function catchupRelativeToArticle(below, id) { cmode: 0, ids: ids_to_mark.toString() }; xhrPost("backend.php", query, (transport) => { - App.handleRpcJson(transport); + Utils.handleRpcJson(transport); }); } } @@ -1489,7 +1489,7 @@ function initHeadlinesMenu() { menu.addChild(new dijit.MenuItem({ label: __("Mark feed as read"), onClick: function () { - catchupFeedInGroup(this.getParent().currentTarget.getAttribute("data-feed-id")); + Feeds.catchupFeedInGroup(this.getParent().currentTarget.getAttribute("data-feed-id")); } })); -- cgit v1.2.3-54-g00ecf From 1d82bd4f19de40f0cf966545c372595caa2c8afe Mon Sep 17 00:00:00 2001 From: Andrew Dolgov Date: Sat, 1 Dec 2018 17:42:21 +0300 Subject: further objectification --- index.php | 6 +- js/functions.js | 110 +++++++------ js/tt-rss.js | 449 ++++++++++++++++++++++++--------------------------- js/viewfeed.js | 181 +++++++++++---------- plugins/note/note.js | 2 +- 5 files changed, 364 insertions(+), 384 deletions(-) (limited to 'js/tt-rss.js') diff --git a/index.php b/index.php index 820db9073..8b4b954ef 100644 --- a/index.php +++ b/index.php @@ -139,7 +139,7 @@ @@ -187,7 +187,7 @@
"; + onchange=\"Headlines.onActionChanged(this)\">"; $reply .= ""; @@ -299,7 +299,7 @@ class Feeds extends Handler_Protected { $label_cache = $line["label_cache"]; $labels = false; - $mouseover_attrs = "onmouseover='postMouseIn(event, $id)' onmouseout='postMouseOut($id)'"; + $mouseover_attrs = "onmouseover='Article.mouseIn($id)' onmouseout='Article.mouseOut($id)'"; if ($label_cache) { $label_cache = json_decode($label_cache, true); diff --git a/index.php b/index.php index 8b4b954ef..c8ff3f7c9 100644 --- a/index.php +++ b/index.php @@ -240,18 +240,18 @@
-
-
+
+
-
-
-
+
+
+
-
-
+
+
-
-
+
+
get_hooks(PluginHost::HOOK_ACTION_ITEM) as $p) { @@ -260,7 +260,7 @@ ?> -
+
diff --git a/js/feedlist.js b/js/feedlist.js index ad863f94c..c295bf22b 100644 --- a/js/feedlist.js +++ b/js/feedlist.js @@ -6,6 +6,7 @@ const Feeds = { infscroll_disabled: 0, _infscroll_timeout: false, _search_query: false, + last_search_query: [], _viewfeed_wait_timeout: false, _counters_prev: [], // NOTE: this implementation is incomplete @@ -206,7 +207,7 @@ const Feeds = { Utils.setLoadingProgress(50); - document.onkeydown = App.hotkeyHandler; + document.onkeydown = () => { App.hotkeyHandler(event) }; window.setInterval(() => { hotkeyPrefixTimeout() }, 3 * 1000); window.setInterval(() => { Headlines.catchupBatchedArticles() }, 10 * 1000); @@ -436,7 +437,7 @@ const Feeds = { str = __("Mark %w in %s as read?"); } - const mark_what = last_search_query && last_search_query[0] ? __("search results") : __("all articles"); + const mark_what = this.last_search_query && this.last_search_query[0] ? __("search results") : __("all articles"); const fn = this.getFeedName(feed, is_cat); str = str.replace("%s", fn) @@ -448,8 +449,8 @@ const Feeds = { const catchup_query = { op: 'rpc', method: 'catchupFeed', feed_id: feed, - is_cat: is_cat, mode: mode, search_query: last_search_query[0], - search_lang: last_search_query[1] + is_cat: is_cat, mode: mode, search_query: this.last_search_query[0], + search_lang: this.last_search_query[1] }; notify_progress("Loading, please wait...", true); diff --git a/js/functions.js b/js/functions.js index 1a0fca484..b6d86b51c 100755 --- a/js/functions.js +++ b/js/functions.js @@ -1025,7 +1025,7 @@ function uploadIconHandler(rc) { switch (rc) { case 0: notify_info("Upload complete."); - if (inPreferences()) { + if (App.isPrefs()) { Feeds.reload(); } else { setTimeout('Feeds.reload(false, false)', 50); @@ -1050,7 +1050,7 @@ function removeFeedIcon(id) { xhrPost("backend.php", query, (transport) => { notify_info("Feed icon removed."); - if (inPreferences()) { + if (App.isPrefs()) { Feeds.reload(); } else { setTimeout('Feeds.reload(false, false)', 50); @@ -1090,7 +1090,7 @@ function addLabel(select, callback) { xhrPost("backend.php", query, (transport) => { if (callback) { callback(transport); - } else if (inPreferences()) { + } else if (App.isPrefs()) { updateLabelList(); } else { Feeds.reload(); @@ -1317,7 +1317,7 @@ function editFilterTest(query) { function quickAddFilter() { let query; - if (!inPreferences()) { + if (!App.isPrefs()) { query = { op: "pref-filters", method: "newfilter", feed: Feeds.getActiveFeedId(), is_cat: Feeds.activeFeedIsCat() }; } else { @@ -1385,7 +1385,7 @@ function quickAddFilter() { const query = dojo.formToQuery("filter_new_form"); xhrPost("backend.php", query, (transport) => { - if (inPreferences()) { + if (App.isPrefs()) { updateFilterList(); } @@ -1395,7 +1395,7 @@ function quickAddFilter() { }, href: "backend.php?" + dojo.objectToQuery(query)}); - if (!inPreferences()) { + if (!App.isPrefs()) { const selectedText = getSelectionText(); const lh = dojo.connect(dialog, "onLoad", function(){ @@ -1453,7 +1453,7 @@ function unsubscribeFeed(feed_id, title) { xhrPost("backend.php", query, (transport) => { if (dijit.byId("feedEditDlg")) dijit.byId("feedEditDlg").hide(); - if (inPreferences()) { + if (App.isPrefs()) { Feeds.reload(); } else { if (feed_id == Feeds.getActiveFeedId()) diff --git a/js/prefs.js b/js/prefs.js index a9417cf3c..8308a747f 100755 --- a/js/prefs.js +++ b/js/prefs.js @@ -65,7 +65,7 @@ const App = { }); }, initSecondStage: function() { - document.onkeydown = this.hotkeyHandler; + document.onkeydown = () => { App.hotkeyHandler(event) }; Utils.setLoadingProgress(50); notify(""); @@ -111,8 +111,11 @@ const App = { console.log("unhandled action: " + action_name + "; keycode: " + event.which); } } + }, + isPrefs: function() { + return true; } -} +}; function notify_callback2(transport, sticky) { notify_info(transport.responseText, sticky); @@ -909,10 +912,6 @@ function labelColorReset() { } } -function inPreferences() { - return true; -} - function editProfiles() { if (dijit.byId("profileEditDlg")) diff --git a/js/tt-rss.js b/js/tt-rss.js index 02cf1ddb6..46f100e27 100644 --- a/js/tt-rss.js +++ b/js/tt-rss.js @@ -1,10 +1,9 @@ /* global dijit, __ */ -let hotkey_actions = {}; - const App = { global_unread: -1, _widescreen_mode: false, + hotkey_actions: {}, init: function() { window.onerror = function (message, filename, lineno, colno, error) { @@ -57,7 +56,7 @@ const App = { return false; Utils.setLoadingProgress(30); - init_hotkey_actions(); + App.initHotkeyActions(); const a = document.createElement('audio'); const hasAudio = !!a.canPlayType; @@ -179,7 +178,7 @@ const App = { const action_name = Utils.keyeventToAction(event); if (action_name) { - const action_func = hotkey_actions[action_name]; + const action_func = this.hotkey_actions[action_name]; if (action_func != null) { action_func(); @@ -233,331 +232,328 @@ const App = { xhrPost("backend.php", {op: "rpc", method: "setpanelmode", wide: wide ? 1 : 0}); }, -}; + initHotkeyActions: function() { + this.hotkey_actions["next_feed"] = function () { + const rv = dijit.byId("feedTree").getNextFeed( + Feeds.getActiveFeedId(), Feeds.activeFeedIsCat()); -function init_hotkey_actions() { - hotkey_actions["next_feed"] = function () { - const rv = dijit.byId("feedTree").getNextFeed( - Feeds.getActiveFeedId(), Feeds.activeFeedIsCat()); - - if (rv) Feeds.viewfeed({feed: rv[0], is_cat: rv[1], delayed: true}) - }; - hotkey_actions["prev_feed"] = function () { - const rv = dijit.byId("feedTree").getPreviousFeed( - Feeds.getActiveFeedId(), Feeds.activeFeedIsCat()); - - if (rv) Feeds.viewfeed({feed: rv[0], is_cat: rv[1], delayed: true}) - }; - hotkey_actions["next_article"] = function () { - Headlines.moveToPost('next'); - }; - hotkey_actions["prev_article"] = function () { - Headlines.moveToPost('prev'); - }; - hotkey_actions["next_article_noscroll"] = function () { - Headlines.moveToPost('next', true); - }; - hotkey_actions["prev_article_noscroll"] = function () { - Headlines.moveToPost('prev', true); - }; - hotkey_actions["next_article_noexpand"] = function () { - Headlines.moveToPost('next', true, true); - }; - hotkey_actions["prev_article_noexpand"] = function () { - Headlines.moveToPost('prev', true, true); - }; - hotkey_actions["search_dialog"] = function () { - Feeds.search(); - }; - hotkey_actions["toggle_mark"] = function () { - Headlines.selectionToggleMarked(); - }; - hotkey_actions["toggle_publ"] = function () { - Headlines.selectionTogglePublished(); - }; - hotkey_actions["toggle_unread"] = function () { - Headlines.selectionToggleUnread({no_error: 1}); - }; - hotkey_actions["edit_tags"] = function () { - const id = Article.getActiveArticleId(); - if (id) { - Article.editArticleTags(id); - } - } - hotkey_actions["open_in_new_window"] = function () { - if (Article.getActiveArticleId()) { - Article.openArticleInNewWindow(Article.getActiveArticleId()); - } - }; - hotkey_actions["catchup_below"] = function () { - catchupRelativeToArticle(1); - }; - hotkey_actions["catchup_above"] = function () { - catchupRelativeToArticle(0); - }; - hotkey_actions["article_scroll_down"] = function () { - scrollArticle(40); - }; - hotkey_actions["article_scroll_up"] = function () { - scrollArticle(-40); - }; - hotkey_actions["close_article"] = function () { - if (App.isCombinedMode()) { - Article.cdmCollapseActive(); - } else { - Article.closeArticlePanel(); - } - }; - hotkey_actions["email_article"] = function () { - if (typeof emailArticle != "undefined") { - emailArticle(); - } else if (typeof mailtoArticle != "undefined") { - mailtoArticle(); - } else { - alert(__("Please enable mail plugin first.")); - } - }; - hotkey_actions["select_all"] = function () { - Headlines.selectArticles('all'); - }; - hotkey_actions["select_unread"] = function () { - Headlines.selectArticles('unread'); - }; - hotkey_actions["select_marked"] = function () { - Headlines.selectArticles('marked'); - }; - hotkey_actions["select_published"] = function () { - Headlines.selectArticles('published'); - }; - hotkey_actions["select_invert"] = function () { - Headlines.selectArticles('invert'); - }; - hotkey_actions["select_none"] = function () { - Headlines.selectArticles('none'); - }; - hotkey_actions["feed_refresh"] = function () { - if (Feeds.getActiveFeedId() != undefined) { - Feeds.viewfeed({feed: Feeds.getActiveFeedId(), is_cat: Feeds.activeFeedIsCat()}); - } - }; - hotkey_actions["feed_unhide_read"] = function () { - Feeds.toggleDispRead(); - }; - hotkey_actions["feed_subscribe"] = function () { - CommonDialogs.quickAddFeed(); - }; - hotkey_actions["feed_debug_update"] = function () { - if (!Feeds.activeFeedIsCat() && parseInt(Feeds.getActiveFeedId()) > 0) { - window.open("backend.php?op=feeds&method=update_debugger&feed_id=" + Feeds.getActiveFeedId() + - "&csrf_token=" + getInitParam("csrf_token")); - } else { - alert("You can't debug this kind of feed."); - } - }; - - hotkey_actions["feed_debug_viewfeed"] = function () { - Feeds.viewfeed({feed: Feeds.getActiveFeedId(), is_cat: Feeds.activeFeedIsCat(), viewfeed_debug: true}); - }; - - hotkey_actions["feed_edit"] = function () { - if (Feeds.activeFeedIsCat()) - alert(__("You can't edit this kind of feed.")); - else - editFeed(Feeds.getActiveFeedId()); - }; - hotkey_actions["feed_catchup"] = function () { - if (Feeds.getActiveFeedId() != undefined) { - Feeds.catchupCurrentFeed(); - } - }; - hotkey_actions["feed_reverse"] = function () { - Headlines.reverseHeadlineOrder(); - }; - hotkey_actions["feed_toggle_vgroup"] = function () { - xhrPost("backend.php", {op: "rpc", method: "togglepref", key: "VFEED_GROUP_BY_FEED"}, () => { - Feeds.viewCurrentFeed(); - }) - }; - hotkey_actions["catchup_all"] = function () { - Feeds.catchupAllFeeds(); - }; - hotkey_actions["cat_toggle_collapse"] = function () { - if (Feeds.activeFeedIsCat()) { - dijit.byId("feedTree").collapseCat(Feeds.getActiveFeedId()); - } - }; - hotkey_actions["goto_all"] = function () { - Feeds.viewfeed({feed: -4}); - }; - hotkey_actions["goto_fresh"] = function () { - Feeds.viewfeed({feed: -3}); - }; - hotkey_actions["goto_marked"] = function () { - Feeds.viewfeed({feed: -1}); - }; - hotkey_actions["goto_published"] = function () { - Feeds.viewfeed({feed: -2}); - }; - hotkey_actions["goto_tagcloud"] = function () { - Utils.displayDlg(__("Tag cloud"), "printTagCloud"); - }; - hotkey_actions["goto_prefs"] = function () { - gotoPreferences(); - }; - hotkey_actions["select_article_cursor"] = function () { - const id = getArticleUnderPointer(); - if (id) { - const row = $("RROW-" + id); - - if (row) { - const cb = dijit.getEnclosingWidget( - row.select(".rchk")[0]); - - if (cb) { - if (!row.hasClassName("active")) - cb.attr("checked", !cb.attr("checked")); - - toggleSelectRowById(cb, "RROW-" + id); - return false; - } + if (rv) Feeds.viewfeed({feed: rv[0], is_cat: rv[1], delayed: true}) + }; + this.hotkey_actions["prev_feed"] = function () { + const rv = dijit.byId("feedTree").getPreviousFeed( + Feeds.getActiveFeedId(), Feeds.activeFeedIsCat()); + + if (rv) Feeds.viewfeed({feed: rv[0], is_cat: rv[1], delayed: true}) + }; + this.hotkey_actions["next_article"] = function () { + Headlines.moveToPost('next'); + }; + this.hotkey_actions["prev_article"] = function () { + Headlines.moveToPost('prev'); + }; + this.hotkey_actions["next_article_noscroll"] = function () { + Headlines.moveToPost('next', true); + }; + this.hotkey_actions["prev_article_noscroll"] = function () { + Headlines.moveToPost('prev', true); + }; + this.hotkey_actions["next_article_noexpand"] = function () { + Headlines.moveToPost('next', true, true); + }; + this.hotkey_actions["prev_article_noexpand"] = function () { + Headlines.moveToPost('prev', true, true); + }; + this.hotkey_actions["search_dialog"] = function () { + Feeds.search(); + }; + this.hotkey_actions["toggle_mark"] = function () { + Headlines.selectionToggleMarked(); + }; + this.hotkey_actions["toggle_publ"] = function () { + Headlines.selectionTogglePublished(); + }; + this.hotkey_actions["toggle_unread"] = function () { + Headlines.selectionToggleUnread({no_error: 1}); + }; + this.hotkey_actions["edit_tags"] = function () { + const id = Article.getActiveArticleId(); + if (id) { + Article.editArticleTags(id); } } - }; - hotkey_actions["create_label"] = function () { - addLabel(); - }; - hotkey_actions["create_filter"] = function () { - quickAddFilter(); - }; - hotkey_actions["collapse_sidebar"] = function () { - Feeds.viewCurrentFeed(); - }; - hotkey_actions["toggle_embed_original"] = function () { - if (typeof embedOriginalArticle != "undefined") { - if (Article.getActiveArticleId()) - embedOriginalArticle(Article.getActiveArticleId()); - } else { - alert(__("Please enable embed_original plugin first.")); - } - }; - hotkey_actions["toggle_widescreen"] = function () { - if (!App.isCombinedMode()) { - App._widescreen_mode = !App._widescreen_mode; + this.hotkey_actions["open_in_new_window"] = function () { + if (Article.getActiveArticleId()) { + Article.openArticleInNewWindow(Article.getActiveArticleId()); + } + }; + this.hotkey_actions["catchup_below"] = function () { + Headlines.catchupRelativeToArticle(1); + }; + this.hotkey_actions["catchup_above"] = function () { + Headlines.catchupRelativeToArticle(0); + }; + this.hotkey_actions["article_scroll_down"] = function () { + Article.scrollArticle(40); + }; + this.hotkey_actions["article_scroll_up"] = function () { + Article.scrollArticle(-40); + }; + this.hotkey_actions["close_article"] = function () { + if (App.isCombinedMode()) { + Article.cdmCollapseActive(); + } else { + Article.closeArticlePanel(); + } + }; + this.hotkey_actions["email_article"] = function () { + if (typeof emailArticle != "undefined") { + emailArticle(); + } else if (typeof mailtoArticle != "undefined") { + mailtoArticle(); + } else { + alert(__("Please enable mail plugin first.")); + } + }; + this.hotkey_actions["select_all"] = function () { + Headlines.selectArticles('all'); + }; + this.hotkey_actions["select_unread"] = function () { + Headlines.selectArticles('unread'); + }; + this.hotkey_actions["select_marked"] = function () { + Headlines.selectArticles('marked'); + }; + this.hotkey_actions["select_published"] = function () { + Headlines.selectArticles('published'); + }; + this.hotkey_actions["select_invert"] = function () { + Headlines.selectArticles('invert'); + }; + this.hotkey_actions["select_none"] = function () { + Headlines.selectArticles('none'); + }; + this.hotkey_actions["feed_refresh"] = function () { + if (Feeds.getActiveFeedId() != undefined) { + Feeds.viewfeed({feed: Feeds.getActiveFeedId(), is_cat: Feeds.activeFeedIsCat()}); + } + }; + this.hotkey_actions["feed_unhide_read"] = function () { + Feeds.toggleDispRead(); + }; + this.hotkey_actions["feed_subscribe"] = function () { + CommonDialogs.quickAddFeed(); + }; + this.hotkey_actions["feed_debug_update"] = function () { + if (!Feeds.activeFeedIsCat() && parseInt(Feeds.getActiveFeedId()) > 0) { + window.open("backend.php?op=feeds&method=update_debugger&feed_id=" + Feeds.getActiveFeedId() + + "&csrf_token=" + getInitParam("csrf_token")); + } else { + alert("You can't debug this kind of feed."); + } + }; - // reset stored sizes because geometry changed - setCookie("ttrss_ci_width", 0); - setCookie("ttrss_ci_height", 0); + this.hotkey_actions["feed_debug_viewfeed"] = function () { + Feeds.viewfeed({feed: Feeds.getActiveFeedId(), is_cat: Feeds.activeFeedIsCat(), viewfeed_debug: true}); + }; - App.switchPanelMode(App._widescreen_mode); - } else { - alert(__("Widescreen is not available in combined mode.")); - } - }; - hotkey_actions["help_dialog"] = function () { - Utils.helpDialog("main"); - }; - hotkey_actions["toggle_combined_mode"] = function () { - notify_progress("Loading, please wait..."); + this.hotkey_actions["feed_edit"] = function () { + if (Feeds.activeFeedIsCat()) + alert(__("You can't edit this kind of feed.")); + else + editFeed(Feeds.getActiveFeedId()); + }; + this.hotkey_actions["feed_catchup"] = function () { + if (Feeds.getActiveFeedId() != undefined) { + Feeds.catchupCurrentFeed(); + } + }; + this.hotkey_actions["feed_reverse"] = function () { + Headlines.reverseHeadlineOrder(); + }; + this.hotkey_actions["feed_toggle_vgroup"] = function () { + xhrPost("backend.php", {op: "rpc", method: "togglepref", key: "VFEED_GROUP_BY_FEED"}, () => { + Feeds.viewCurrentFeed(); + }) + }; + this.hotkey_actions["catchup_all"] = function () { + Feeds.catchupAllFeeds(); + }; + this.hotkey_actions["cat_toggle_collapse"] = function () { + if (Feeds.activeFeedIsCat()) { + dijit.byId("feedTree").collapseCat(Feeds.getActiveFeedId()); + } + }; + this.hotkey_actions["goto_all"] = function () { + Feeds.viewfeed({feed: -4}); + }; + this.hotkey_actions["goto_fresh"] = function () { + Feeds.viewfeed({feed: -3}); + }; + this.hotkey_actions["goto_marked"] = function () { + Feeds.viewfeed({feed: -1}); + }; + this.hotkey_actions["goto_published"] = function () { + Feeds.viewfeed({feed: -2}); + }; + this.hotkey_actions["goto_tagcloud"] = function () { + Utils.displayDlg(__("Tag cloud"), "printTagCloud"); + }; + this.hotkey_actions["goto_prefs"] = function () { + document.location.href = "prefs.php"; + }; + this.hotkey_actions["select_article_cursor"] = function () { + const id = Article.getArticleUnderPointer(); + if (id) { + const row = $("RROW-" + id); - const value = App.isCombinedMode() ? "false" : "true"; + if (row) { + const cb = dijit.getEnclosingWidget( + row.select(".rchk")[0]); - xhrPost("backend.php", {op: "rpc", method: "setpref", key: "COMBINED_DISPLAY_MODE", value: value}, () => { - setInitParam("combined_display_mode", - !getInitParam("combined_display_mode")); + if (cb) { + if (!row.hasClassName("active")) + cb.attr("checked", !cb.attr("checked")); - Article.closeArticlePanel(); + toggleSelectRowById(cb, "RROW-" + id); + return false; + } + } + } + }; + this.hotkey_actions["create_label"] = function () { + addLabel(); + }; + this.hotkey_actions["create_filter"] = function () { + quickAddFilter(); + }; + this.hotkey_actions["collapse_sidebar"] = function () { Feeds.viewCurrentFeed(); - }) - }; - hotkey_actions["toggle_cdm_expanded"] = function () { - notify_progress("Loading, please wait..."); + }; + this.hotkey_actions["toggle_embed_original"] = function () { + if (typeof embedOriginalArticle != "undefined") { + if (Article.getActiveArticleId()) + embedOriginalArticle(Article.getActiveArticleId()); + } else { + alert(__("Please enable embed_original plugin first.")); + } + }; + this.hotkey_actions["toggle_widescreen"] = function () { + if (!App.isCombinedMode()) { + App._widescreen_mode = !App._widescreen_mode; - const value = getInitParam("cdm_expanded") ? "false" : "true"; + // reset stored sizes because geometry changed + setCookie("ttrss_ci_width", 0); + setCookie("ttrss_ci_height", 0); - xhrPost("backend.php", {op: "rpc", method: "setpref", key: "CDM_EXPANDED", value: value}, () => { - setInitParam("cdm_expanded", !getInitParam("cdm_expanded")); - Feeds.viewCurrentFeed(); - }); - }; -} + App.switchPanelMode(App._widescreen_mode); + } else { + alert(__("Widescreen is not available in combined mode.")); + } + }; + this.hotkey_actions["help_dialog"] = function () { + Utils.helpDialog("main"); + }; + this.hotkey_actions["toggle_combined_mode"] = function () { + notify_progress("Loading, please wait..."); -function quickMenuGo(opid) { - switch (opid) { - case "qmcPrefs": - gotoPreferences(); - break; - case "qmcLogout": - document.location.href = "backend.php?op=logout"; - break; - case "qmcTagCloud": - Utils.displayDlg(__("Tag cloud"), "printTagCloud"); - break; - case "qmcSearch": - Feeds.search(); - break; - case "qmcAddFeed": - CommonDialogs.quickAddFeed(); - break; - case "qmcDigest": - window.location.href = "backend.php?op=digest"; - break; - case "qmcEditFeed": - if (Feeds.activeFeedIsCat()) - alert(__("You can't edit this kind of feed.")); - else - editFeed(Feeds.getActiveFeedId()); - break; - case "qmcRemoveFeed": - var actid = Feeds.getActiveFeedId(); - - if (Feeds.activeFeedIsCat()) { - alert(__("You can't unsubscribe from the category.")); - return; - } + const value = App.isCombinedMode() ? "false" : "true"; - if (!actid) { - alert(__("Please select some feed first.")); - return; - } + xhrPost("backend.php", {op: "rpc", method: "setpref", key: "COMBINED_DISPLAY_MODE", value: value}, () => { + setInitParam("combined_display_mode", + !getInitParam("combined_display_mode")); + + Article.closeArticlePanel(); + Feeds.viewCurrentFeed(); + }) + }; + this.hotkey_actions["toggle_cdm_expanded"] = function () { + notify_progress("Loading, please wait..."); - var fn = Feeds.getFeedName(actid); + const value = getInitParam("cdm_expanded") ? "false" : "true"; - var pr = __("Unsubscribe from %s?").replace("%s", fn); + xhrPost("backend.php", {op: "rpc", method: "setpref", key: "CDM_EXPANDED", value: value}, () => { + setInitParam("cdm_expanded", !getInitParam("cdm_expanded")); + Feeds.viewCurrentFeed(); + }); + }; + }, + onActionSelected: function(opid) { + switch (opid) { + case "qmcPrefs": + gotoPreferences(); + break; + case "qmcLogout": + document.location.href = "backend.php?op=logout"; + break; + case "qmcTagCloud": + Utils.displayDlg(__("Tag cloud"), "printTagCloud"); + break; + case "qmcSearch": + Feeds.search(); + break; + case "qmcAddFeed": + CommonDialogs.quickAddFeed(); + break; + case "qmcDigest": + window.location.href = "backend.php?op=digest"; + break; + case "qmcEditFeed": + if (Feeds.activeFeedIsCat()) + alert(__("You can't edit this kind of feed.")); + else + editFeed(Feeds.getActiveFeedId()); + break; + case "qmcRemoveFeed": + var actid = Feeds.getActiveFeedId(); + + if (Feeds.activeFeedIsCat()) { + alert(__("You can't unsubscribe from the category.")); + return; + } - if (confirm(pr)) { - unsubscribeFeed(actid); - } - break; - case "qmcCatchupAll": - Feeds.catchupAllFeeds(); - break; - case "qmcShowOnlyUnread": - Feeds.toggleDispRead(); - break; - case "qmcToggleWidescreen": - if (!App.isCombinedMode()) { - App._widescreen_mode = !App._widescreen_mode; - - // reset stored sizes because geometry changed - setCookie("ttrss_ci_width", 0); - setCookie("ttrss_ci_height", 0); - - App.switchPanelMode(App._widescreen_mode); - } else { - alert(__("Widescreen is not available in combined mode.")); + if (!actid) { + alert(__("Please select some feed first.")); + return; + } + + var fn = Feeds.getFeedName(actid); + + var pr = __("Unsubscribe from %s?").replace("%s", fn); + + if (confirm(pr)) { + unsubscribeFeed(actid); + } + break; + case "qmcCatchupAll": + Feeds.catchupAllFeeds(); + break; + case "qmcShowOnlyUnread": + Feeds.toggleDispRead(); + break; + case "qmcToggleWidescreen": + if (!App.isCombinedMode()) { + App._widescreen_mode = !App._widescreen_mode; + + // reset stored sizes because geometry changed + setCookie("ttrss_ci_width", 0); + setCookie("ttrss_ci_height", 0); + + App.switchPanelMode(App._widescreen_mode); + } else { + alert(__("Widescreen is not available in combined mode.")); + } + break; + case "qmcHKhelp": + Utils.helpDialog("main"); + break; + default: + console.log("quickMenuGo: unknown action: " + opid); } - break; - case "qmcHKhelp": - Utils.helpDialog("main"); - break; - default: - console.log("quickMenuGo: unknown action: " + opid); + }, + isPrefs: function() { + return false; } -} - -function inPreferences() { - return false; -} +}; function hash_get(key) { const kv = window.location.hash.substring(1).toQueryParams(); @@ -569,7 +565,3 @@ function hash_set(key, value) { kv[key] = value; window.location.hash = $H(kv).toQueryString(); } - -function gotoPreferences() { - document.location.href = "prefs.php"; -} diff --git a/js/viewfeed.js b/js/viewfeed.js index cbbea8a05..e8995712a 100755 --- a/js/viewfeed.js +++ b/js/viewfeed.js @@ -1,8 +1,5 @@ /* global dijit, __, ngettext */ -let post_under_pointer = false; -let last_search_query; - const ArticleCache = { has_storage: 'sessionStorage' in window && window['sessionStorage'] !== null, set: function(id, obj) { @@ -118,7 +115,7 @@ const Article = { c.attr('content', article); PluginHost.run(PluginHost.HOOK_ARTICLE_RENDERED, c.domNode); - correctHeadlinesOffset(Article.getActiveArticleId()); + Headlines.correctHeadlinesOffset(Article.getActiveArticleId()); try { c.focus(); @@ -126,7 +123,7 @@ const Article = { } }, view: function(id, noexpand) { - Article.setActiveArticleId(id); + this.setActiveArticleId(id); if (!noexpand) { console.log("loading article", id); @@ -135,7 +132,7 @@ const Article = { /* only request uncached articles */ - getRelativePostIds(id).each((n) => { + this.getRelativePostIds(id).each((n) => { if (!ArticleCache.get(n)) cids.push(n); }); @@ -313,6 +310,49 @@ const Article = { }, getActiveArticleId: function() { return this._active_article_id; + }, + scrollArticle: function(offset) { + if (!App.isCombinedMode()) { + const ci = $("content-insert"); + if (ci) { + ci.scrollTop += offset; + } + } else { + const hi = $("headlines-frame"); + if (hi) { + hi.scrollTop += offset; + } + + } + }, + getRelativePostIds: function(id, limit) { + + const tmp = []; + + if (!limit) limit = 6; //3 + + const ids = Headlines.getLoadedArticleIds(); + + for (let i = 0; i < ids.length; i++) { + if (ids[i] == id) { + for (let k = 1; k <= limit; k++) { + //if (i > k-1) tmp.push(ids[i-k]); + if (i < ids.length - k) tmp.push(ids[i + k]); + } + break; + } + } + + return tmp; + }, + mouseIn: function(id) { + this.post_under_pointer = id; + }, + mouseOut: function(id) { + this.post_under_pointer = false; + }, + getArticleUnderPointer: function() { + return this.post_under_pointer; } }; @@ -485,7 +525,7 @@ const Headlines = { ft.firstChild.innerHTML = "" + ft.firstChild.innerHTML; - initFloatingMenu(); + this.initFloatingMenu(); const cb = ft.select(".rchk")[0]; @@ -546,7 +586,7 @@ const Headlines = { is_cat = reply['headlines']['is_cat']; feed_id = reply['headlines']['id']; - last_search_query = reply['headlines']['search_query']; + Feeds.last_search_query = reply['headlines']['search_query']; if (feed_id != -7 && (feed_id != Feeds.getActiveFeedId() || is_cat != Feeds.activeFeedIsCat())) return; @@ -602,7 +642,7 @@ const Headlines = { if (!hsp) hsp = new Element("DIV", {"id": "headlines-spacer"}); dijit.byId('headlines-frame').domNode.appendChild(hsp); - initHeadlinesMenu(); + this.initHeadlinesMenu(); if (Feeds.infscroll_disabled) hsp.innerHTML = "" + @@ -646,7 +686,7 @@ const Headlines = { markHeadline(ids[i]); } */ - initHeadlinesMenu(); + this.initHeadlinesMenu(); if (Feeds.infscroll_disabled) { hsp.innerHTML = "" + @@ -894,7 +934,7 @@ const Headlines = { if (!noscroll && article && article.offsetTop + article.offsetHeight > ctr.scrollTop + ctr.offsetHeight) { - scrollArticle(ctr.offsetHeight / 4); + Article.scrollArticle(ctr.offsetHeight / 4); } else if (next_id) { Article.setActiveArticleId(next_id); @@ -902,7 +942,7 @@ const Headlines = { } } else if (next_id) { - correctHeadlinesOffset(next_id); + Headlines.correctHeadlinesOffset(next_id); Article.view(next_id, noexpand); } } @@ -917,17 +957,17 @@ const Headlines = { const ctr = $("headlines-frame"); if (!noscroll && article && article.offsetTop < ctr.scrollTop) { - scrollArticle(-ctr.offsetHeight / 3); + Article.scrollArticle(-ctr.offsetHeight / 3); } else if (!noscroll && prev_article && prev_article.offsetTop < ctr.scrollTop) { - scrollArticle(-ctr.offsetHeight / 4); + Article.scrollArticle(-ctr.offsetHeight / 4); } else if (prev_id) { Article.setActiveArticleId(prev_id); Article.cdmScrollToArticleId(prev_id, noscroll); } } else if (prev_id) { - correctHeadlinesOffset(prev_id); + Headlines.correctHeadlinesOffset(prev_id); Article.view(prev_id, noexpand); } } @@ -986,7 +1026,7 @@ const Headlines = { xhrPost("backend.php", query, (transport) => { Utils.handleRpcJson(transport); - updateHeadlineLabels(transport); + this.onLabelsUpdated(transport); }); }, selectionAssignLabel: function(id, ids) { @@ -1004,7 +1044,7 @@ const Headlines = { xhrPost("backend.php", query, (transport) => { Utils.handleRpcJson(transport); - updateHeadlineLabels(transport); + this.onLabelsUpdated(transport); }); }, deleteSelection: function() { @@ -1212,362 +1252,306 @@ const Headlines = { } else { if (callback) callback(); } - } -}; - -function postMouseIn(e, id) { - post_under_pointer = id; -} - -function postMouseOut(id) { - post_under_pointer = false; -} - -function catchupRelativeToArticle(below, id) { + }, + catchupRelativeToArticle: function(below, id) { - if (!id) id = Article.getActiveArticleId(); + if (!id) id = Article.getActiveArticleId(); - if (!id) { - alert(__("No article is selected.")); - return; - } + if (!id) { + alert(__("No article is selected.")); + return; + } - const visible_ids = Headlines.getLoadedArticleIds(); + const visible_ids = this.getLoadedArticleIds(); - const ids_to_mark = []; + const ids_to_mark = []; - if (!below) { - for (let i = 0; i < visible_ids.length; i++) { - if (visible_ids[i] != id) { - const e = $("RROW-" + visible_ids[i]); + if (!below) { + for (let i = 0; i < visible_ids.length; i++) { + if (visible_ids[i] != id) { + const e = $("RROW-" + visible_ids[i]); - if (e && e.hasClassName("Unread")) { - ids_to_mark.push(visible_ids[i]); + if (e && e.hasClassName("Unread")) { + ids_to_mark.push(visible_ids[i]); + } + } else { + break; } - } else { - break; } - } - } else { - for (let i = visible_ids.length - 1; i >= 0; i--) { - if (visible_ids[i] != id) { - const e = $("RROW-" + visible_ids[i]); + } else { + for (let i = visible_ids.length - 1; i >= 0; i--) { + if (visible_ids[i] != id) { + const e = $("RROW-" + visible_ids[i]); - if (e && e.hasClassName("Unread")) { - ids_to_mark.push(visible_ids[i]); + if (e && e.hasClassName("Unread")) { + ids_to_mark.push(visible_ids[i]); + } + } else { + break; } - } else { - break; } } - } - if (ids_to_mark.length == 0) { - alert(__("No articles found to mark")); - } else { - const msg = ngettext("Mark %d article as read?", "Mark %d articles as read?", ids_to_mark.length).replace("%d", ids_to_mark.length); + if (ids_to_mark.length == 0) { + alert(__("No articles found to mark")); + } else { + const msg = ngettext("Mark %d article as read?", "Mark %d articles as read?", ids_to_mark.length).replace("%d", ids_to_mark.length); - if (getInitParam("confirm_feed_catchup") != 1 || confirm(msg)) { + if (getInitParam("confirm_feed_catchup") != 1 || confirm(msg)) { - for (var i = 0; i < ids_to_mark.length; i++) { - var e = $("RROW-" + ids_to_mark[i]); - e.removeClassName("Unread"); - } + for (var i = 0; i < ids_to_mark.length; i++) { + var e = $("RROW-" + ids_to_mark[i]); + e.removeClassName("Unread"); + } - const query = { op: "rpc", method: "catchupSelected", - cmode: 0, ids: ids_to_mark.toString() }; + const query = { + op: "rpc", method: "catchupSelected", + cmode: 0, ids: ids_to_mark.toString() + }; - xhrPost("backend.php", query, (transport) => { - Utils.handleRpcJson(transport); + xhrPost("backend.php", query, (transport) => { + Utils.handleRpcJson(transport); + }); + } + } + }, + onLabelsUpdated: function(transport) { + const data = JSON.parse(transport.responseText); + + if (data) { + data['info-for-headlines'].each(function (elem) { + $$(".HLLCTR-" + elem.id).each(function (ctr) { + ctr.innerHTML = elem.labels; + }); }); } - } -} + }, + onActionChanged: function(elem) { + eval(elem.value); + elem.attr('value', 'false'); + }, + correctHeadlinesOffset: function(id) { + const container = $("headlines-frame"); + const row = $("RROW-" + id); -function getArticleUnderPointer() { - return post_under_pointer; -} + if (!container || !row) return; -function scrollArticle(offset) { - if (!App.isCombinedMode()) { - const ci = $("content-insert"); - if (ci) { - ci.scrollTop += offset; - } - } else { - const hi = $("headlines-frame"); - if (hi) { - hi.scrollTop += offset; - } + const viewport = container.offsetHeight; - } -} + const rel_offset_top = row.offsetTop - container.scrollTop; + const rel_offset_bottom = row.offsetTop + row.offsetHeight - container.scrollTop; -function updateHeadlineLabels(transport) { - const data = JSON.parse(transport.responseText); + //console.log("Rtop: " + rel_offset_top + " Rbtm: " + rel_offset_bottom); + //console.log("Vport: " + viewport); - if (data) { - data['info-for-headlines'].each(function (elem) { - $$(".HLLCTR-" + elem.id).each(function (ctr) { - ctr.innerHTML = elem.labels; - }); - }); - } -} + if (rel_offset_top <= 0 || rel_offset_top > viewport) { + container.scrollTop = row.offsetTop; + } else if (rel_offset_bottom > viewport) { + container.scrollTop = row.offsetTop + row.offsetHeight - viewport; + } + }, + initFloatingMenu: function() { + if (!dijit.byId("floatingMenu")) { -function getRelativePostIds(id, limit) { + const menu = new dijit.Menu({ + id: "floatingMenu", + targetNodeIds: ["floatingTitle"] + }); - const tmp = []; + this.headlinesMenuCommon(menu); - if (!limit) limit = 6; //3 + menu.startup(); + } + }, + headlinesMenuCommon: function(menu) { - const ids = Headlines.getLoadedArticleIds(); + menu.addChild(new dijit.MenuItem({ + label: __("Open original article"), + onClick: function (event) { + Article.openArticleInNewWindow(this.getParent().currentTarget.getAttribute("data-article-id")); + } + })); - for (let i = 0; i < ids.length; i++) { - if (ids[i] == id) { - for (let k = 1; k <= limit; k++) { - //if (i > k-1) tmp.push(ids[i-k]); - if (i < ids.length - k) tmp.push(ids[i + k]); + menu.addChild(new dijit.MenuItem({ + label: __("Display article URL"), + onClick: function (event) { + Article.displayArticleUrl(this.getParent().currentTarget.getAttribute("data-article-id")); } - break; - } - } + })); - return tmp; -} + menu.addChild(new dijit.MenuSeparator()); -function correctHeadlinesOffset(id) { - const container = $("headlines-frame"); - const row = $("RROW-" + id); + menu.addChild(new dijit.MenuItem({ + label: __("Toggle unread"), + onClick: function () { - if (!container || !row) return; + let ids = Headlines.getSelectedArticleIds2(); + // cast to string + const id = (this.getParent().currentTarget.getAttribute("data-article-id")) + ""; + ids = ids.length != 0 && ids.indexOf(id) != -1 ? ids : [id]; - const viewport = container.offsetHeight; + Headlines.selectionToggleUnread({ids: ids, no_error: 1}); + } + })); - const rel_offset_top = row.offsetTop - container.scrollTop; - const rel_offset_bottom = row.offsetTop + row.offsetHeight - container.scrollTop; + menu.addChild(new dijit.MenuItem({ + label: __("Toggle starred"), + onClick: function () { + let ids = Headlines.getSelectedArticleIds2(); + // cast to string + const id = (this.getParent().currentTarget.getAttribute("data-article-id")) + ""; + ids = ids.length != 0 && ids.indexOf(id) != -1 ? ids : [id]; - //console.log("Rtop: " + rel_offset_top + " Rbtm: " + rel_offset_bottom); - //console.log("Vport: " + viewport); + Headlines.selectionToggleMarked(ids); + } + })); - if (rel_offset_top <= 0 || rel_offset_top > viewport) { - container.scrollTop = row.offsetTop; - } else if (rel_offset_bottom > viewport) { - container.scrollTop = row.offsetTop + row.offsetHeight - viewport; - } -} + menu.addChild(new dijit.MenuItem({ + label: __("Toggle published"), + onClick: function () { + let ids = Headlines.getSelectedArticleIds2(); + // cast to string + const id = (this.getParent().currentTarget.getAttribute("data-article-id")) + ""; + ids = ids.length != 0 && ids.indexOf(id) != -1 ? ids : [id]; -function headlineActionsChange(elem) { - eval(elem.value); - elem.attr('value', 'false'); -} + Headlines.selectionTogglePublished(ids); + } + })); -function initFloatingMenu() { - if (!dijit.byId("floatingMenu")) { + menu.addChild(new dijit.MenuSeparator()); - const menu = new dijit.Menu({ - id: "floatingMenu", - targetNodeIds: ["floatingTitle"] - }); + menu.addChild(new dijit.MenuItem({ + label: __("Mark above as read"), + onClick: function () { + Headlines.catchupRelativeToArticle(0, this.getParent().currentTarget.getAttribute("data-article-id")); + } + })); - headlinesMenuCommon(menu); + menu.addChild(new dijit.MenuItem({ + label: __("Mark below as read"), + onClick: function () { + Headlines.catchupRelativeToArticle(1, this.getParent().currentTarget.getAttribute("data-article-id")); + } + })); - menu.startup(); - } -} -function headlinesMenuCommon(menu) { + const labels = getInitParam("labels"); - menu.addChild(new dijit.MenuItem({ - label: __("Open original article"), - onClick: function (event) { - Article.openArticleInNewWindow(this.getParent().currentTarget.getAttribute("data-article-id")); - } - })); + if (labels && labels.length) { - menu.addChild(new dijit.MenuItem({ - label: __("Display article URL"), - onClick: function (event) { - Article.displayArticleUrl(this.getParent().currentTarget.getAttribute("data-article-id")); - } - })); + menu.addChild(new dijit.MenuSeparator()); - menu.addChild(new dijit.MenuSeparator()); + const labelAddMenu = new dijit.Menu({ownerMenu: menu}); + const labelDelMenu = new dijit.Menu({ownerMenu: menu}); - menu.addChild(new dijit.MenuItem({ - label: __("Toggle unread"), - onClick: function () { + labels.each(function (label) { + const bare_id = label.id; + const name = label.caption; - let ids = Headlines.getSelectedArticleIds2(); - // cast to string - const id = (this.getParent().currentTarget.getAttribute("data-article-id")) + ""; - ids = ids.length != 0 && ids.indexOf(id) != -1 ? ids : [id]; + labelAddMenu.addChild(new dijit.MenuItem({ + label: name, + labelId: bare_id, + onClick: function () { - Headlines.selectionToggleUnread({ids: ids, no_error: 1}); - } - })); + let ids = Headlines.getSelectedArticleIds2(); + // cast to string + const id = (this.getParent().ownerMenu.currentTarget.getAttribute("data-article-id")) + ""; - menu.addChild(new dijit.MenuItem({ - label: __("Toggle starred"), - onClick: function () { - let ids = Headlines.getSelectedArticleIds2(); - // cast to string - const id = (this.getParent().currentTarget.getAttribute("data-article-id")) + ""; - ids = ids.length != 0 && ids.indexOf(id) != -1 ? ids : [id]; + ids = ids.length != 0 && ids.indexOf(id) != -1 ? ids : [id]; - Headlines.selectionToggleMarked(ids); - } - })); + Headlines.selectionAssignLabel(this.labelId, ids); + } + })); - menu.addChild(new dijit.MenuItem({ - label: __("Toggle published"), - onClick: function () { - let ids = Headlines.getSelectedArticleIds2(); - // cast to string - const id = (this.getParent().currentTarget.getAttribute("data-article-id")) + ""; - ids = ids.length != 0 && ids.indexOf(id) != -1 ? ids : [id]; + labelDelMenu.addChild(new dijit.MenuItem({ + label: name, + labelId: bare_id, + onClick: function () { + let ids = Headlines.getSelectedArticleIds2(); + // cast to string + const id = (this.getParent().ownerMenu.currentTarget.getAttribute("data-article-id")) + ""; - Headlines.selectionTogglePublished(ids); - } - })); + ids = ids.length != 0 && ids.indexOf(id) != -1 ? ids : [id]; - menu.addChild(new dijit.MenuSeparator()); + Headlines.selectionRemoveLabel(this.labelId, ids); + } + })); - menu.addChild(new dijit.MenuItem({ - label: __("Mark above as read"), - onClick: function () { - catchupRelativeToArticle(0, this.getParent().currentTarget.getAttribute("data-article-id")); - } - })); + }); - menu.addChild(new dijit.MenuItem({ - label: __("Mark below as read"), - onClick: function () { - catchupRelativeToArticle(1, this.getParent().currentTarget.getAttribute("data-article-id")); - } - })); + menu.addChild(new dijit.PopupMenuItem({ + label: __("Assign label"), + popup: labelAddMenu + })); + menu.addChild(new dijit.PopupMenuItem({ + label: __("Remove label"), + popup: labelDelMenu + })); - const labels = getInitParam("labels"); + } + }, + initHeadlinesMenu: function() { + if (!dijit.byId("headlinesMenu")) { - if (labels && labels.length) { + const menu = new dijit.Menu({ + id: "headlinesMenu", + targetNodeIds: ["headlines-frame"], + selector: ".hlMenuAttach" + }); - menu.addChild(new dijit.MenuSeparator()); + this.headlinesMenuCommon(menu); - const labelAddMenu = new dijit.Menu({ownerMenu: menu}); - const labelDelMenu = new dijit.Menu({ownerMenu: menu}); + menu.startup(); + } - labels.each(function (label) { - const bare_id = label.id; - const name = label.caption; + /* vgroup feed title menu */ - labelAddMenu.addChild(new dijit.MenuItem({ - label: name, - labelId: bare_id, - onClick: function () { + if (!dijit.byId("headlinesFeedTitleMenu")) { - let ids = Headlines.getSelectedArticleIds2(); - // cast to string - const id = (this.getParent().ownerMenu.currentTarget.getAttribute("data-article-id")) + ""; + const menu = new dijit.Menu({ + id: "headlinesFeedTitleMenu", + targetNodeIds: ["headlines-frame"], + selector: "div.cdmFeedTitle" + }); - ids = ids.length != 0 && ids.indexOf(id) != -1 ? ids : [id]; + menu.addChild(new dijit.MenuItem({ + label: __("Select articles in group"), + onClick: function (event) { + Headlines.selectArticles("all", + "#headlines-frame > div[id*=RROW]" + + "[data-orig-feed-id='" + this.getParent().currentTarget.getAttribute("data-feed-id") + "']"); - Headlines.selectionAssignLabel(this.labelId, ids); } })); - labelDelMenu.addChild(new dijit.MenuItem({ - label: name, - labelId: bare_id, + menu.addChild(new dijit.MenuItem({ + label: __("Mark group as read"), onClick: function () { - let ids = Headlines.getSelectedArticleIds2(); - // cast to string - const id = (this.getParent().ownerMenu.currentTarget.getAttribute("data-article-id")) + ""; - - ids = ids.length != 0 && ids.indexOf(id) != -1 ? ids : [id]; + Headlines.selectArticles("none"); + Headlines.selectArticles("all", + "#headlines-frame > div[id*=RROW]" + + "[data-orig-feed-id='" + this.getParent().currentTarget.getAttribute("data-feed-id") + "']"); - Headlines.selectionRemoveLabel(this.labelId, ids); + Headlines.catchupSelection(); } })); - }); - - menu.addChild(new dijit.PopupMenuItem({ - label: __("Assign label"), - popup: labelAddMenu - })); - - menu.addChild(new dijit.PopupMenuItem({ - label: __("Remove label"), - popup: labelDelMenu - })); - - } -} - -function initHeadlinesMenu() { - if (!dijit.byId("headlinesMenu")) { - - const menu = new dijit.Menu({ - id: "headlinesMenu", - targetNodeIds: ["headlines-frame"], - selector: ".hlMenuAttach" - }); - - headlinesMenuCommon(menu); - - menu.startup(); - } - - /* vgroup feed title menu */ - - if (!dijit.byId("headlinesFeedTitleMenu")) { - - const menu = new dijit.Menu({ - id: "headlinesFeedTitleMenu", - targetNodeIds: ["headlines-frame"], - selector: "div.cdmFeedTitle" - }); - - menu.addChild(new dijit.MenuItem({ - label: __("Select articles in group"), - onClick: function (event) { - Headlines.selectArticles("all", - "#headlines-frame > div[id*=RROW]" + - "[data-orig-feed-id='" + this.getParent().currentTarget.getAttribute("data-feed-id") + "']"); - - } - })); - - menu.addChild(new dijit.MenuItem({ - label: __("Mark group as read"), - onClick: function () { - Headlines.selectArticles("none"); - Headlines.selectArticles("all", - "#headlines-frame > div[id*=RROW]" + - "[data-orig-feed-id='" + this.getParent().currentTarget.getAttribute("data-feed-id") + "']"); - - Headlines.catchupSelection(); - } - })); - - menu.addChild(new dijit.MenuItem({ - label: __("Mark feed as read"), - onClick: function () { - Feeds.catchupFeedInGroup(this.getParent().currentTarget.getAttribute("data-feed-id")); - } - })); + menu.addChild(new dijit.MenuItem({ + label: __("Mark feed as read"), + onClick: function () { + Feeds.catchupFeedInGroup(this.getParent().currentTarget.getAttribute("data-feed-id")); + } + })); - menu.addChild(new dijit.MenuItem({ - label: __("Edit feed"), - onClick: function () { - editFeed(this.getParent().currentTarget.getAttribute("data-feed-id")); - } - })); + menu.addChild(new dijit.MenuItem({ + label: __("Edit feed"), + onClick: function () { + editFeed(this.getParent().currentTarget.getAttribute("data-feed-id")); + } + })); - menu.startup(); + menu.startup(); + } } -} - - - +}; -- cgit v1.2.3-54-g00ecf From bc96eac2ac6579bfe7a4d99292c0ada3412dc54c Mon Sep 17 00:00:00 2001 From: Andrew Dolgov Date: Sat, 1 Dec 2018 22:19:20 +0300 Subject: addLabel -> CommonDialogs --- js/functions.js | 48 +++++++++++++++++++++++------------------------- js/prefs.js | 2 +- js/tt-rss.js | 4 ++-- 3 files changed, 26 insertions(+), 28 deletions(-) (limited to 'js/tt-rss.js') diff --git a/js/functions.js b/js/functions.js index 04a81d925..f4e422aec 100755 --- a/js/functions.js +++ b/js/functions.js @@ -651,6 +651,29 @@ const CommonDialogs = { }); dialog.show(); + }, + addLabel: function(select, callback) { + const caption = prompt(__("Please enter label caption:"), ""); + + if (caption != undefined && caption.trim().length > 0) { + + const query = {op: "pref-labels", method: "add", caption: caption.trim()}; + + if (select) + Object.extend(query, {output: "select"}); + + notify_progress("Loading, please wait...", true); + + xhrPost("backend.php", query, (transport) => { + if (callback) { + callback(transport); + } else if (App.isPrefs()) { + updateLabelList(); + } else { + Feeds.reload(); + } + }); + } } }; @@ -1067,31 +1090,6 @@ function uploadFeedIcon() { return false; } -function addLabel(select, callback) { - const caption = prompt(__("Please enter label caption:"), ""); - - if (caption != undefined && caption.trim().length > 0) { - - const query = { op: "pref-labels", method: "add", caption: caption.trim() }; - - if (select) - Object.extend(query, {output: "select"}); - - notify_progress("Loading, please wait...", true); - - xhrPost("backend.php", query, (transport) => { - if (callback) { - callback(transport); - } else if (App.isPrefs()) { - updateLabelList(); - } else { - Feeds.reload(); - } - }); - } - -} - function createNewRuleElement(parentNode, replaceNode) { const form = document.forms["filter_new_rule_form"]; const query = { op: "pref-filters", method: "printrulename", rule: dojo.formToJson(form) }; diff --git a/js/prefs.js b/js/prefs.js index 1541d49d0..67be0b474 100755 --- a/js/prefs.js +++ b/js/prefs.js @@ -97,7 +97,7 @@ const App = { CommonDialogs.quickAddFeed(); return false; case "create_label": - addLabel(); + CommonDialogs.addLabel(); return false; case "create_filter": quickAddFilter(); diff --git a/js/tt-rss.js b/js/tt-rss.js index 46f100e27..6dd4a91eb 100644 --- a/js/tt-rss.js +++ b/js/tt-rss.js @@ -421,7 +421,7 @@ const App = { } }; this.hotkey_actions["create_label"] = function () { - addLabel(); + CommonDialogs.addLabel(); }; this.hotkey_actions["create_filter"] = function () { quickAddFilter(); @@ -480,7 +480,7 @@ const App = { onActionSelected: function(opid) { switch (opid) { case "qmcPrefs": - gotoPreferences(); + document.location.href = "prefs.php"; break; case "qmcLogout": document.location.href = "backend.php?op=logout"; -- cgit v1.2.3-54-g00ecf From 1e2d4410d320fcee644add76293f229741a163cb Mon Sep 17 00:00:00 2001 From: Andrew Dolgov Date: Sat, 1 Dec 2018 22:39:29 +0300 Subject: move some more shared stuff to CommonDialogs, Filters, and Utils --- classes/dlg.php | 2 +- classes/pref/feeds.php | 8 +- classes/pref/filters.php | 4 +- js/FeedTree.js | 2 +- js/PrefFeedTree.js | 4 +- js/functions.js | 877 ++++++++++++++++++++-------------------- js/prefs.js | 6 +- js/tt-rss.js | 8 +- js/viewfeed.js | 2 +- plugins/af_psql_trgm/init.php | 2 +- plugins/af_readability/init.php | 2 +- tests/functional/BasicTest.php | 2 +- 12 files changed, 463 insertions(+), 456 deletions(-) (limited to 'js/tt-rss.js') diff --git a/classes/dlg.php b/classes/dlg.php index 50cbd12dd..02249ea96 100644 --- a/classes/dlg.php +++ b/classes/dlg.php @@ -174,7 +174,7 @@ class Dlg extends Handler_Protected { print "
"; - print " "; print ""; print "
"; @@ -1247,7 +1247,7 @@ class Pref_Feeds extends Handler_Protected { var bare_id = id.substr(id.indexOf(':')+1); if (id.match('FEED:')) { - editFeed(bare_id); + CommonDialogs.editFeed(bare_id); } else if (id.match('CAT:')) { editCat(bare_id, item); } @@ -1441,7 +1441,7 @@ class Pref_Feeds extends Handler_Protected { print "
". + "onclick=\"CommonDialogs.editFeed(".$line["id"].")\">". htmlspecialchars($line["title"]).""; print ""; @@ -1506,7 +1506,7 @@ class Pref_Feeds extends Handler_Protected { print "". + "onclick=\"CommonDialogs.editFeed(".$line["id"].")\">". htmlspecialchars($line["title"]).": "; print ""; diff --git a/classes/pref/filters.php b/classes/pref/filters.php index e3503d545..e60628f8f 100755 --- a/classes/pref/filters.php +++ b/classes/pref/filters.php @@ -797,7 +797,7 @@ class Pref_Filters extends Handler_Protected { dojoType=\"dijit.MenuItem\">".__('None')."
"; print "
"; - print " "; print " "; print " -- cgit v1.2.3-54-g00ecf From 874560db547f718b82d77657dc019d840c30e0ed Mon Sep 17 00:00:00 2001 From: Andrew Dolgov Date: Sun, 2 Dec 2018 10:33:58 +0300 Subject: remove obsolete row selection functions move getUrlParam() to Utils --- classes/feeds.php | 4 ++-- classes/pref/feeds.php | 4 ++-- classes/pref/filters.php | 4 ++-- classes/pref/prefs.php | 6 ++--- classes/pref/users.php | 2 +- include/feedbrowser.php | 4 ++-- include/functions.php | 2 +- js/functions.js | 61 +++++++++++++----------------------------------- js/prefs.js | 6 ++--- js/tt-rss.js | 2 +- js/viewfeed.js | 8 +++++++ 11 files changed, 41 insertions(+), 62 deletions(-) (limited to 'js/tt-rss.js') diff --git a/classes/feeds.php b/classes/feeds.php index c9e5ca496..b32521130 100755 --- a/classes/feeds.php +++ b/classes/feeds.php @@ -406,7 +406,7 @@ class Feeds extends Handler_Protected { $reply['content'] .= "
"; $reply['content'] .= ""; $reply['content'] .= "$marked_pic"; @@ -505,7 +505,7 @@ class Feeds extends Handler_Protected { $tmp_content .= "
"; $tmp_content .= ""; $tmp_content .= "$marked_pic"; diff --git a/classes/pref/feeds.php b/classes/pref/feeds.php index f47d24501..efc76701e 100755 --- a/classes/pref/feeds.php +++ b/classes/pref/feeds.php @@ -1435,7 +1435,7 @@ class Pref_Feeds extends Handler_Protected { # id needed for selectTableRows() print ""; print ""; @@ -1500,7 +1500,7 @@ class Pref_Feeds extends Handler_Protected { # id needed for selectTableRows() print ""; print ""; diff --git a/classes/pref/filters.php b/classes/pref/filters.php index e48615395..f9b4bfb2a 100755 --- a/classes/pref/filters.php +++ b/classes/pref/filters.php @@ -429,7 +429,7 @@ class Pref_Filters extends Handler_Protected { $data = htmlspecialchars(json_encode($line)); - print "
  • ". + print "
  • ". "".$this->getRuleName($line)."". "
  • "; } @@ -473,7 +473,7 @@ class Pref_Filters extends Handler_Protected { $data = htmlspecialchars(json_encode($line)); - print "
  • ". + print "
  • ". "".$this->getActionName($line)."". "
  • "; } diff --git a/classes/pref/prefs.php b/classes/pref/prefs.php index 82456f342..017f2e06c 100644 --- a/classes/pref/prefs.php +++ b/classes/pref/prefs.php @@ -799,7 +799,7 @@ class Pref_Prefs extends Handler_Protected { $plugin_icon = $checked ? "plugin.png" : "plugin_disabled.png"; - print ""; @@ -1023,7 +1023,7 @@ class Pref_Prefs extends Handler_Protected { print ""; @@ -1050,7 +1050,7 @@ class Pref_Prefs extends Handler_Protected { $edit_title = htmlspecialchars($line["title"]); print ""; diff --git a/classes/pref/users.php b/classes/pref/users.php index 1e6eae227..eda3e1a0e 100644 --- a/classes/pref/users.php +++ b/classes/pref/users.php @@ -419,7 +419,7 @@ class Pref_Users extends Handler_Protected { $line["created"] = make_local_datetime($line["created"], false); $line["last_login"] = make_local_datetime($line["last_login"], false); - print ""; diff --git a/include/feedbrowser.php b/include/feedbrowser.php index a0b1b6e8f..4f37241ea 100644 --- a/include/feedbrowser.php +++ b/include/feedbrowser.php @@ -53,7 +53,7 @@ $site_url = htmlspecialchars($line["site_url"]); $subscribers = $line["subscribers"]; - $check_box = ""; @@ -73,7 +73,7 @@ $feed_url = htmlspecialchars($line["feed_url"]); $site_url = htmlspecialchars($line["site_url"]); - $check_box = ""; if ($line['articles_archived'] > 0) { diff --git a/include/functions.php b/include/functions.php index f6d09fe67..2ec42c7ee 100755 --- a/include/functions.php +++ b/include/functions.php @@ -1244,7 +1244,7 @@ "g t" => "goto_tagcloud", "g *p" => "goto_prefs", // "other" => array( - "(9)|Tab" => "select_article_cursor", // tab + "r" => "select_article_cursor", "c l" => "create_label", "c f" => "create_filter", "c s" => "collapse_sidebar", diff --git a/js/functions.js b/js/functions.js index ce6d7aca9..033933794 100755 --- a/js/functions.js +++ b/js/functions.js @@ -53,8 +53,8 @@ Array.prototype.remove = function(s) { } }; -const ListUtils = { - onChecked: function(elem) { +const Lists = { + onRowChecked: function(elem) { // account for dojo checkboxes elem = elem.domNode || elem; @@ -62,11 +62,23 @@ const ListUtils = { } }; +const Tables = { + onRowChecked: function(elem) { + // account for dojo checkboxes + elem = elem.domNode || elem; + + elem.up("tr").toggleClassName("Selected"); + } +} + const Utils = { _rpc_seq: 0, hotkey_prefix: 0, hotkey_prefix_pressed: false, hotkey_prefix_timeout: 0, + urlParam: function(param) { + return String(window.location.href).parseQuery()[param]; + }, next_seq: function() { this._rpc_seq += 1; return this._rpc_seq; @@ -988,43 +1000,6 @@ function getCookie(name) { return unescape(dc.substring(begin + prefix.length, end)); } -function toggleSelectRowById(sender, id) { - const row = $(id); - return toggleSelectRow(sender, row); -} - -/* this is for dijit Checkbox */ -function toggleSelectRow2(sender, row, is_cdm) { - - if (!row) - if (!is_cdm) - row = sender.domNode.parentNode.parentNode; - else - row = sender.domNode.parentNode.parentNode.parentNode; // oh ffs - - if (sender.checked && !row.hasClassName('Selected')) - row.addClassName('Selected'); - else - row.removeClassName('Selected'); - - if (typeof Headlines != "undefined") - Headlines.updateSelectedPrompt(); -} - - -function toggleSelectRow(sender, row) { - - if (!row) row = sender.parentNode.parentNode; - - if (sender.checked && !row.hasClassName('Selected')) - row.addClassName('Selected'); - else - row.removeClassName('Selected'); - - if (typeof Headlines != "undefined") - Headlines.updateSelectedPrompt(); -} - // noinspection JSUnusedGlobalSymbols function displayIfChecked(checkbox, elemId) { if (checkbox.checked) { @@ -1034,10 +1009,6 @@ function displayIfChecked(checkbox, elemId) { } } -function getURLParam(param){ - return String(window.location.href).parseQuery()[param]; -} - // noinspection JSUnusedGlobalSymbols function closeInfoBox() { const dialog = dijit.byId("infoBox"); @@ -1140,7 +1111,7 @@ const Filters = { new dijit.form.CheckBox({ onChange: function () { - ListUtils.onChecked(this); + Lists.onRowChecked(this); }, }, cb); @@ -1189,7 +1160,7 @@ const Filters = { new dijit.form.CheckBox({ onChange: function () { - ListUtils.onChecked(this); + Lists.onRowChecked(this); }, }, cb); diff --git a/js/prefs.js b/js/prefs.js index 40068b95c..f12c31441 100755 --- a/js/prefs.js +++ b/js/prefs.js @@ -69,17 +69,17 @@ const App = { Utils.setLoadingProgress(50); notify(""); - let tab = getURLParam('tab'); + let tab = Utils.urlParam('tab'); if (tab) { tab = dijit.byId(tab + "Tab"); if (tab) dijit.byId("pref-tabs").selectChild(tab); } - const method = getURLParam('method'); + const method = Utils.urlParam('method'); if (method == 'editFeed') { - const param = getURLParam('methodparam'); + const param = Utils.urlParam('methodparam'); window.setTimeout(function () { CommonDialogs.editFeed(param) diff --git a/js/tt-rss.js b/js/tt-rss.js index b337e0ae5..71bb2337a 100644 --- a/js/tt-rss.js +++ b/js/tt-rss.js @@ -414,7 +414,7 @@ const App = { if (!row.hasClassName("active")) cb.attr("checked", !cb.attr("checked")); - toggleSelectRowById(cb, "RROW-" + id); + Headlines.onRowChecked(cb); return false; } } diff --git a/js/viewfeed.js b/js/viewfeed.js index 93bc56c9d..e7703ed55 100755 --- a/js/viewfeed.js +++ b/js/viewfeed.js @@ -1109,6 +1109,14 @@ const Headlines = { return rv; }, + onRowChecked: function(elem) { + // account for dojo checkboxes + elem = elem.domNode || elem; + + elem.up("div[id*=RROW]").toggleClassName("Selected"); + + this.updateSelectedPrompt(); + }, select: function(mode) { // mode = all,none,unread,invert,marked,published let query = "#headlines-frame > div[id*=RROW]"; -- cgit v1.2.3-54-g00ecf From fda3ad39c8d89b07d4ead691bacdca6865e46517 Mon Sep 17 00:00:00 2001 From: Andrew Dolgov Date: Sun, 2 Dec 2018 17:00:58 +0300 Subject: split several utility objects into separate dojo modules --- js/CommonDialogs.js | 392 ++++++++++++++++++ js/CommonFilters.js | 389 ++++++++++++++++++ js/PrefHelpers.js | 152 +++++++ js/PrefUsers.js | 119 ++++++ js/Utils.js | 338 ++++++++++++++++ js/functions.js | 1116 --------------------------------------------------- js/prefs.js | 287 +------------ js/tt-rss.js | 13 +- 8 files changed, 1420 insertions(+), 1386 deletions(-) create mode 100644 js/CommonDialogs.js create mode 100644 js/CommonFilters.js create mode 100644 js/PrefHelpers.js create mode 100644 js/PrefUsers.js create mode 100644 js/Utils.js (limited to 'js/tt-rss.js') diff --git a/js/CommonDialogs.js b/js/CommonDialogs.js new file mode 100644 index 000000000..757f84f81 --- /dev/null +++ b/js/CommonDialogs.js @@ -0,0 +1,392 @@ +define(["dojo/_base/declare"], function (declare) { + return declare("fox.CommonDialogs", null, { + quickAddFeed: function() { + const query = "backend.php?op=feeds&method=quickAddFeed"; + + // overlapping widgets + if (dijit.byId("batchSubDlg")) dijit.byId("batchSubDlg").destroyRecursive(); + if (dijit.byId("feedAddDlg")) dijit.byId("feedAddDlg").destroyRecursive(); + + const dialog = new dijit.Dialog({ + id: "feedAddDlg", + title: __("Subscribe to Feed"), + style: "width: 600px", + show_error: function (msg) { + const elem = $("fadd_error_message"); + + elem.innerHTML = msg; + + if (!Element.visible(elem)) + new Effect.Appear(elem); + + }, + execute: function () { + if (this.validate()) { + console.log(dojo.objectToQuery(this.attr('value'))); + + const feed_url = this.attr('value').feed; + + Element.show("feed_add_spinner"); + Element.hide("fadd_error_message"); + + xhrPost("backend.php", this.attr('value'), (transport) => { + try { + + try { + var reply = JSON.parse(transport.responseText); + } catch (e) { + Element.hide("feed_add_spinner"); + alert(__("Failed to parse output. This can indicate server timeout and/or network issues. Backend output was logged to browser console.")); + console.log('quickAddFeed, backend returned:' + transport.responseText); + return; + } + + const rc = reply['result']; + + notify(''); + Element.hide("feed_add_spinner"); + + console.log(rc); + + switch (parseInt(rc['code'])) { + case 1: + dialog.hide(); + notify_info(__("Subscribed to %s").replace("%s", feed_url)); + + Feeds.reload(); + break; + case 2: + dialog.show_error(__("Specified URL seems to be invalid.")); + break; + case 3: + dialog.show_error(__("Specified URL doesn't seem to contain any feeds.")); + break; + case 4: + const feeds = rc['feeds']; + + Element.show("fadd_multiple_notify"); + + const select = dijit.byId("feedDlg_feedContainerSelect"); + + while (select.getOptions().length > 0) + select.removeOption(0); + + select.addOption({value: '', label: __("Expand to select feed")}); + + let count = 0; + for (const feedUrl in feeds) { + if (feeds.hasOwnProperty(feedUrl)) { + select.addOption({value: feedUrl, label: feeds[feedUrl]}); + count++; + } + } + + Effect.Appear('feedDlg_feedsContainer', {duration: 0.5}); + + break; + case 5: + dialog.show_error(__("Couldn't download the specified URL: %s").replace("%s", rc['message'])); + break; + case 6: + dialog.show_error(__("XML validation failed: %s").replace("%s", rc['message'])); + break; + case 0: + dialog.show_error(__("You are already subscribed to this feed.")); + break; + } + + } catch (e) { + console.error(transport.responseText); + exception_error(e); + } + }); + } + }, + href: query + }); + + dialog.show(); + }, + showFeedsWithErrors: function() { + const query = {op: "pref-feeds", method: "feedsWithErrors"}; + + if (dijit.byId("errorFeedsDlg")) + dijit.byId("errorFeedsDlg").destroyRecursive(); + + const dialog = new dijit.Dialog({ + id: "errorFeedsDlg", + title: __("Feeds with update errors"), + style: "width: 600px", + getSelectedFeeds: function () { + return Tables.getSelected("prefErrorFeedList"); + }, + removeSelected: function () { + const sel_rows = this.getSelectedFeeds(); + + if (sel_rows.length > 0) { + if (confirm(__("Remove selected feeds?"))) { + notify_progress("Removing selected feeds...", true); + + const query = { + op: "pref-feeds", method: "remove", + ids: sel_rows.toString() + }; + + xhrPost("backend.php", query, () => { + notify(''); + dialog.hide(); + Feeds.reload(); + }); + } + + } else { + alert(__("No feeds selected.")); + } + }, + execute: function () { + if (this.validate()) { + // + } + }, + href: "backend.php?" + dojo.objectToQuery(query) + }); + + dialog.show(); + }, + feedBrowser: function() { + const query = {op: "feeds", method: "feedBrowser"}; + + if (dijit.byId("feedAddDlg")) + dijit.byId("feedAddDlg").hide(); + + if (dijit.byId("feedBrowserDlg")) + dijit.byId("feedBrowserDlg").destroyRecursive(); + + // noinspection JSUnusedGlobalSymbols + const dialog = new dijit.Dialog({ + id: "feedBrowserDlg", + title: __("More Feeds"), + style: "width: 600px", + getSelectedFeedIds: function () { + const list = $$("#browseFeedList li[id*=FBROW]"); + const selected = []; + + list.each(function (child) { + const id = child.id.replace("FBROW-", ""); + + if (child.hasClassName('Selected')) { + selected.push(id); + } + }); + + return selected; + }, + getSelectedFeeds: function () { + const list = $$("#browseFeedList li.Selected"); + const selected = []; + + list.each(function (child) { + const title = child.getElementsBySelector("span.fb_feedTitle")[0].innerHTML; + const url = child.getElementsBySelector("a.fb_feedUrl")[0].href; + + selected.push([title, url]); + + }); + + return selected; + }, + + subscribe: function () { + const mode = this.attr('value').mode; + let selected = []; + + if (mode == "1") + selected = this.getSelectedFeeds(); + else + selected = this.getSelectedFeedIds(); + + if (selected.length > 0) { + dijit.byId("feedBrowserDlg").hide(); + + notify_progress("Loading, please wait...", true); + + const query = { + op: "rpc", method: "massSubscribe", + payload: JSON.stringify(selected), mode: mode + }; + + xhrPost("backend.php", query, () => { + notify(''); + Feeds.reload(); + }); + + } else { + alert(__("No feeds selected.")); + } + + }, + update: function () { + Element.show('feed_browser_spinner'); + + xhrPost("backend.php", dialog.attr("value"), (transport) => { + notify(''); + + Element.hide('feed_browser_spinner'); + + const reply = JSON.parse(transport.responseText); + const mode = reply['mode']; + + if ($("browseFeedList") && reply['content']) { + $("browseFeedList").innerHTML = reply['content']; + } + + dojo.parser.parse("browseFeedList"); + + if (mode == 2) { + Element.show(dijit.byId('feed_archive_remove').domNode); + } else { + Element.hide(dijit.byId('feed_archive_remove').domNode); + } + }); + }, + removeFromArchive: function () { + const selected = this.getSelectedFeedIds(); + + if (selected.length > 0) { + if (confirm(__("Remove selected feeds from the archive? Feeds with stored articles will not be removed."))) { + Element.show('feed_browser_spinner'); + + const query = {op: "rpc", method: "remarchive", ids: selected.toString()}; + + xhrPost("backend.php", query, () => { + dialog.update(); + }); + } + } + }, + execute: function () { + if (this.validate()) { + this.subscribe(); + } + }, + href: "backend.php?" + dojo.objectToQuery(query) + }); + + dialog.show(); + }, + addLabel: function(select, callback) { + const caption = prompt(__("Please enter label caption:"), ""); + + if (caption != undefined && caption.trim().length > 0) { + + const query = {op: "pref-labels", method: "add", caption: caption.trim()}; + + if (select) + Object.extend(query, {output: "select"}); + + notify_progress("Loading, please wait...", true); + + xhrPost("backend.php", query, (transport) => { + if (callback) { + callback(transport); + } else if (App.isPrefs()) { + dijit.byId("labelTree").reload(); + } else { + Feeds.reload(); + } + }); + } + }, + unsubscribeFeed: function(feed_id, title) { + + const msg = __("Unsubscribe from %s?").replace("%s", title); + + if (title == undefined || confirm(msg)) { + notify_progress("Removing feed..."); + + const query = {op: "pref-feeds", quiet: 1, method: "remove", ids: feed_id}; + + xhrPost("backend.php", query, () => { + if (dijit.byId("feedEditDlg")) dijit.byId("feedEditDlg").hide(); + + if (App.isPrefs()) { + Feeds.reload(); + } else { + if (feed_id == Feeds.getActive()) + setTimeout(() => { + Feeds.open({feed: -5}) + }, + 100); + + if (feed_id < 0) Feeds.reload(); + } + }); + } + + return false; + }, + editFeed: function (feed) { + if (feed <= 0) + return alert(__("You can't edit this kind of feed.")); + + const query = {op: "pref-feeds", method: "editfeed", id: feed}; + + console.log("editFeed", query); + + if (dijit.byId("filterEditDlg")) + dijit.byId("filterEditDlg").destroyRecursive(); + + if (dijit.byId("feedEditDlg")) + dijit.byId("feedEditDlg").destroyRecursive(); + + const dialog = new dijit.Dialog({ + id: "feedEditDlg", + title: __("Edit Feed"), + style: "width: 600px", + execute: function () { + if (this.validate()) { + notify_progress("Saving data...", true); + + xhrPost("backend.php", dialog.attr('value'), () => { + dialog.hide(); + notify(''); + Feeds.reload(); + }); + } + }, + href: "backend.php?" + dojo.objectToQuery(query) + }); + + dialog.show(); + }, + genUrlChangeKey: function(feed, is_cat) { + if (confirm(__("Generate new syndication address for this feed?"))) { + + notify_progress("Trying to change address...", true); + + const query = {op: "pref-feeds", method: "regenFeedKey", id: feed, is_cat: is_cat}; + + xhrJson("backend.php", query, (reply) => { + const new_link = reply.link; + const e = $('gen_feed_url'); + + if (new_link) { + e.innerHTML = e.innerHTML.replace(/&key=.*$/, + "&key=" + new_link); + + e.href = e.href.replace(/&key=.*$/, + "&key=" + new_link); + + new Effect.Highlight(e); + + notify(''); + + } else { + notify_error("Could not change feed URL."); + } + }); + } + return false; + } + }); +}); \ No newline at end of file diff --git a/js/CommonFilters.js b/js/CommonFilters.js new file mode 100644 index 000000000..28a151690 --- /dev/null +++ b/js/CommonFilters.js @@ -0,0 +1,389 @@ +define(["dojo/_base/declare"], function (declare) { + return declare("fox.CommonFilters", null, { + filterDlgCheckAction: function(sender) { + const action = sender.value; + + const action_param = $("filterDlg_paramBox"); + + if (!action_param) { + console.log("filterDlgCheckAction: can't find action param box!"); + return; + } + + // if selected action supports parameters, enable params field + if (action == 4 || action == 6 || action == 7 || action == 9) { + new Effect.Appear(action_param, {duration: 0.5}); + + Element.hide(dijit.byId("filterDlg_actionParam").domNode); + Element.hide(dijit.byId("filterDlg_actionParamLabel").domNode); + Element.hide(dijit.byId("filterDlg_actionParamPlugin").domNode); + + if (action == 7) { + Element.show(dijit.byId("filterDlg_actionParamLabel").domNode); + } else if (action == 9) { + Element.show(dijit.byId("filterDlg_actionParamPlugin").domNode); + } else { + Element.show(dijit.byId("filterDlg_actionParam").domNode); + } + + } else { + Element.hide(action_param); + } + }, + createNewRuleElement: function(parentNode, replaceNode) { + const form = document.forms["filter_new_rule_form"]; + const query = {op: "pref-filters", method: "printrulename", rule: dojo.formToJson(form)}; + + xhrPost("backend.php", query, (transport) => { + try { + const li = dojo.create("li"); + + const cb = dojo.create("input", {type: "checkbox"}, li); + + new dijit.form.CheckBox({ + onChange: function () { + Lists.onRowChecked(this); + }, + }, cb); + + dojo.create("input", { + type: "hidden", + name: "rule[]", + value: dojo.formToJson(form) + }, li); + + dojo.create("span", { + onclick: function () { + dijit.byId('filterEditDlg').editRule(this); + }, + innerHTML: transport.responseText + }, li); + + if (replaceNode) { + parentNode.replaceChild(li, replaceNode); + } else { + parentNode.appendChild(li); + } + } catch (e) { + exception_error(e); + } + }); + }, + createNewActionElement: function(parentNode, replaceNode) { + const form = document.forms["filter_new_action_form"]; + + if (form.action_id.value == 7) { + form.action_param.value = form.action_param_label.value; + } else if (form.action_id.value == 9) { + form.action_param.value = form.action_param_plugin.value; + } + + const query = { + op: "pref-filters", method: "printactionname", + action: dojo.formToJson(form) + }; + + xhrPost("backend.php", query, (transport) => { + try { + const li = dojo.create("li"); + + const cb = dojo.create("input", {type: "checkbox"}, li); + + new dijit.form.CheckBox({ + onChange: function () { + Lists.onRowChecked(this); + }, + }, cb); + + dojo.create("input", { + type: "hidden", + name: "action[]", + value: dojo.formToJson(form) + }, li); + + dojo.create("span", { + onclick: function () { + dijit.byId('filterEditDlg').editAction(this); + }, + innerHTML: transport.responseText + }, li); + + if (replaceNode) { + parentNode.replaceChild(li, replaceNode); + } else { + parentNode.appendChild(li); + } + + } catch (e) { + exception_error(e); + } + }); + }, + addFilterRule: function(replaceNode, ruleStr) { + if (dijit.byId("filterNewRuleDlg")) + dijit.byId("filterNewRuleDlg").destroyRecursive(); + + const query = "backend.php?op=pref-filters&method=newrule&rule=" + + param_escape(ruleStr); + + const rule_dlg = new dijit.Dialog({ + id: "filterNewRuleDlg", + title: ruleStr ? __("Edit rule") : __("Add rule"), + style: "width: 600px", + execute: function () { + if (this.validate()) { + Filters.createNewRuleElement($("filterDlg_Matches"), replaceNode); + this.hide(); + } + }, + href: query + }); + + rule_dlg.show(); + }, + addFilterAction: function(replaceNode, actionStr) { + if (dijit.byId("filterNewActionDlg")) + dijit.byId("filterNewActionDlg").destroyRecursive(); + + const query = "backend.php?op=pref-filters&method=newaction&action=" + + param_escape(actionStr); + + const rule_dlg = new dijit.Dialog({ + id: "filterNewActionDlg", + title: actionStr ? __("Edit action") : __("Add action"), + style: "width: 600px", + execute: function () { + if (this.validate()) { + Filters.createNewActionElement($("filterDlg_Actions"), replaceNode); + this.hide(); + } + }, + href: query + }); + + rule_dlg.show(); + }, + editFilterTest: function(query) { + + if (dijit.byId("filterTestDlg")) + dijit.byId("filterTestDlg").destroyRecursive(); + + const test_dlg = new dijit.Dialog({ + id: "filterTestDlg", + title: "Test Filter", + style: "width: 600px", + results: 0, + limit: 100, + max_offset: 10000, + getTestResults: function (query, offset) { + const updquery = query + "&offset=" + offset + "&limit=" + test_dlg.limit; + + console.log("getTestResults:" + offset); + + xhrPost("backend.php", updquery, (transport) => { + try { + const result = JSON.parse(transport.responseText); + + if (result && dijit.byId("filterTestDlg") && dijit.byId("filterTestDlg").open) { + test_dlg.results += result.length; + + console.log("got results:" + result.length); + + $("prefFilterProgressMsg").innerHTML = __("Looking for articles (%d processed, %f found)...") + .replace("%f", test_dlg.results) + .replace("%d", offset); + + console.log(offset + " " + test_dlg.max_offset); + + for (let i = 0; i < result.length; i++) { + const tmp = new Element("table"); + tmp.innerHTML = result[i]; + dojo.parser.parse(tmp); + + $("prefFilterTestResultList").innerHTML += tmp.innerHTML; + } + + if (test_dlg.results < 30 && offset < test_dlg.max_offset) { + + // get the next batch + window.setTimeout(function () { + test_dlg.getTestResults(query, offset + test_dlg.limit); + }, 0); + + } else { + // all done + + Element.hide("prefFilterLoadingIndicator"); + + if (test_dlg.results == 0) { + $("prefFilterTestResultList").innerHTML = "No recent articles matching this filter have been found."; + $("prefFilterProgressMsg").innerHTML = "Articles matching this filter:"; + } else { + $("prefFilterProgressMsg").innerHTML = __("Found %d articles matching this filter:") + .replace("%d", test_dlg.results); + } + + } + + } else if (!result) { + console.log("getTestResults: can't parse results object"); + + Element.hide("prefFilterLoadingIndicator"); + + notify_error("Error while trying to get filter test results."); + + } else { + console.log("getTestResults: dialog closed, bailing out."); + } + } catch (e) { + exception_error(e); + } + + }); + }, + href: query + }); + + dojo.connect(test_dlg, "onLoad", null, function (e) { + test_dlg.getTestResults(query, 0); + }); + + test_dlg.show(); + }, + quickAddFilter: function() { + let query; + + if (!App.isPrefs()) { + query = { + op: "pref-filters", method: "newfilter", + feed: Feeds.getActive(), is_cat: Feeds.activeIsCat() + }; + } else { + query = {op: "pref-filters", method: "newfilter"}; + } + + console.log('quickAddFilter', query); + + if (dijit.byId("feedEditDlg")) + dijit.byId("feedEditDlg").destroyRecursive(); + + if (dijit.byId("filterEditDlg")) + dijit.byId("filterEditDlg").destroyRecursive(); + + const dialog = new dijit.Dialog({ + id: "filterEditDlg", + title: __("Create Filter"), + style: "width: 600px", + test: function () { + const query = "backend.php?" + dojo.formToQuery("filter_new_form") + "&savemode=test"; + + Filters.editFilterTest(query); + }, + selectRules: function (select) { + $$("#filterDlg_Matches input[type=checkbox]").each(function (e) { + e.checked = select; + if (select) + e.parentNode.addClassName("Selected"); + else + e.parentNode.removeClassName("Selected"); + }); + }, + selectActions: function (select) { + $$("#filterDlg_Actions input[type=checkbox]").each(function (e) { + e.checked = select; + + if (select) + e.parentNode.addClassName("Selected"); + else + e.parentNode.removeClassName("Selected"); + + }); + }, + editRule: function (e) { + const li = e.parentNode; + const rule = li.getElementsByTagName("INPUT")[1].value; + Filters.addFilterRule(li, rule); + }, + editAction: function (e) { + const li = e.parentNode; + const action = li.getElementsByTagName("INPUT")[1].value; + Filters.addFilterAction(li, action); + }, + addAction: function () { + Filters.addFilterAction(); + }, + addRule: function () { + Filters.addFilterRule(); + }, + deleteAction: function () { + $$("#filterDlg_Actions li[class*=Selected]").each(function (e) { + e.parentNode.removeChild(e) + }); + }, + deleteRule: function () { + $$("#filterDlg_Matches li[class*=Selected]").each(function (e) { + e.parentNode.removeChild(e) + }); + }, + execute: function () { + if (this.validate()) { + + const query = dojo.formToQuery("filter_new_form"); + + xhrPost("backend.php", query, () => { + if (App.isPrefs()) { + dijit.byId("filterTree").reload(); + } + + dialog.hide(); + }); + } + }, + href: "backend.php?" + dojo.objectToQuery(query) + }); + + if (!App.isPrefs()) { + const selectedText = getSelectionText(); + + const lh = dojo.connect(dialog, "onLoad", function () { + dojo.disconnect(lh); + + if (selectedText != "") { + + const feed_id = Feeds.activeIsCat() ? 'CAT:' + parseInt(Feeds.getActive()) : + Feeds.getActive(); + + const rule = {reg_exp: selectedText, feed_id: [feed_id], filter_type: 1}; + + Filters.addFilterRule(null, dojo.toJson(rule)); + + } else { + + const query = {op: "rpc", method: "getlinktitlebyid", id: Article.getActive()}; + + xhrPost("backend.php", query, (transport) => { + const reply = JSON.parse(transport.responseText); + + let title = false; + + if (reply && reply.title) title = reply.title; + + if (title || Feeds.getActive() || Feeds.activeIsCat()) { + + console.log(title + " " + Feeds.getActive()); + + const feed_id = Feeds.activeIsCat() ? 'CAT:' + parseInt(Feeds.getActive()) : + Feeds.getActive(); + + const rule = {reg_exp: title, feed_id: [feed_id], filter_type: 1}; + + Filters.addFilterRule(null, dojo.toJson(rule)); + } + }); + } + }); + } + dialog.show(); + }, + }); +}); diff --git a/js/PrefHelpers.js b/js/PrefHelpers.js new file mode 100644 index 000000000..a2451f478 --- /dev/null +++ b/js/PrefHelpers.js @@ -0,0 +1,152 @@ +define(["dojo/_base/declare"], function (declare) { + return declare("fox.PrefHelpers", null, { + clearFeedAccessKeys: function() { + if (confirm(__("This will invalidate all previously generated feed URLs. Continue?"))) { + notify_progress("Clearing URLs..."); + + xhrPost("backend.php", {op: "pref-feeds", method: "clearKeys"}, () => { + notify_info("Generated URLs cleared."); + }); + } + + return false; + }, + updateEventLog: function() { + xhrPost("backend.php", { op: "pref-system" }, (transport) => { + dijit.byId('systemConfigTab').attr('content', transport.responseText); + notify(""); + }); + }, + clearEventLog: function() { + if (confirm(__("Clear event log?"))) { + + notify_progress("Loading, please wait..."); + + xhrPost("backend.php", {op: "pref-system", method: "clearLog"}, () => { + this.updateEventLog(); + }); + } + }, + editProfiles: function() { + + if (dijit.byId("profileEditDlg")) + dijit.byId("profileEditDlg").destroyRecursive(); + + const query = "backend.php?op=pref-prefs&method=editPrefProfiles"; + + // noinspection JSUnusedGlobalSymbols + const dialog = new dijit.Dialog({ + id: "profileEditDlg", + title: __("Settings Profiles"), + style: "width: 600px", + getSelectedProfiles: function () { + return Tables.getSelected("prefFeedProfileList"); + }, + removeSelected: function () { + const sel_rows = this.getSelectedProfiles(); + + if (sel_rows.length > 0) { + if (confirm(__("Remove selected profiles? Active and default profiles will not be removed."))) { + notify_progress("Removing selected profiles...", true); + + const query = { + op: "rpc", method: "remprofiles", + ids: sel_rows.toString() + }; + + xhrPost("backend.php", query, () => { + notify(''); + Prefs.editProfiles(); + }); + } + + } else { + alert(__("No profiles selected.")); + } + }, + activateProfile: function () { + const sel_rows = this.getSelectedProfiles(); + + if (sel_rows.length == 1) { + if (confirm(__("Activate selected profile?"))) { + notify_progress("Loading, please wait..."); + + xhrPost("backend.php", {op: "rpc", method: "setprofile", id: sel_rows.toString()}, () => { + window.location.reload(); + }); + } + + } else { + alert(__("Please choose a profile to activate.")); + } + }, + addProfile: function () { + if (this.validate()) { + notify_progress("Creating profile...", true); + + const query = {op: "rpc", method: "addprofile", title: dialog.attr('value').newprofile}; + + xhrPost("backend.php", query, () => { + notify(''); + Prefs.editProfiles(); + }); + + } + }, + execute: function () { + if (this.validate()) { + } + }, + href: query + }); + + dialog.show(); + }, + customizeCSS: function() { + const query = "backend.php?op=pref-prefs&method=customizeCSS"; + + if (dijit.byId("cssEditDlg")) + dijit.byId("cssEditDlg").destroyRecursive(); + + const dialog = new dijit.Dialog({ + id: "cssEditDlg", + title: __("Customize stylesheet"), + style: "width: 600px", + execute: function () { + notify_progress('Saving data...', true); + + xhrPost("backend.php", this.attr('value'), () => { + window.location.reload(); + }); + + }, + href: query + }); + + dialog.show(); + }, + confirmReset: function() { + if (confirm(__("Reset to defaults?"))) { + xhrPost("backend.php", {op: "pref-prefs", method: "resetconfig"}, (transport) => { + Prefs.refresh(); + notify_info(transport.responseText); + }); + } + }, + clearPluginData: function(name) { + if (confirm(__("Clear stored data for this plugin?"))) { + notify_progress("Loading, please wait..."); + + xhrPost("backend.php", {op: "pref-prefs", method: "clearplugindata", name: name}, () => { + Prefs.refresh(); + }); + } + }, + refresh: function() { + xhrPost("backend.php", { op: "pref-prefs" }, (transport) => { + dijit.byId('genConfigTab').attr('content', transport.responseText); + notify(""); + }); + } + }); +}); diff --git a/js/PrefUsers.js b/js/PrefUsers.js new file mode 100644 index 000000000..aa3c2826d --- /dev/null +++ b/js/PrefUsers.js @@ -0,0 +1,119 @@ +define(["dojo/_base/declare"], function (declare) { + + return declare("fox.PrefUsers", null, { + reload: function(sort) { + const user_search = $("user_search"); + const search = user_search ? user_search.value : ""; + + xhrPost("backend.php", { op: "pref-users", sort: sort, search: search }, (transport) => { + dijit.byId('userConfigTab').attr('content', transport.responseText); + notify(""); + }); + }, + add: function() { + const login = prompt(__("Please enter username:"), ""); + + if (login) { + notify_progress("Adding user..."); + + xhrPost("backend.php", {op: "pref-users", method: "add", login: login}, (transport) => { + alert(transport.responseText); + Users.reload(); + }); + + } + }, + edit: function(id) { + const query = "backend.php?op=pref-users&method=edit&id=" + + param_escape(id); + + if (dijit.byId("userEditDlg")) + dijit.byId("userEditDlg").destroyRecursive(); + + const dialog = new dijit.Dialog({ + id: "userEditDlg", + title: __("User Editor"), + style: "width: 600px", + execute: function () { + if (this.validate()) { + notify_progress("Saving data...", true); + + xhrPost("backend.php", dojo.formToObject("user_edit_form"), (transport) => { + dialog.hide(); + Users.reload(); + }); + } + }, + href: query + }); + + dialog.show(); + }, + resetSelected: function() { + const rows = this.getSelection(); + + if (rows.length == 0) { + alert(__("No users selected.")); + return; + } + + if (rows.length > 1) { + alert(__("Please select one user.")); + return; + } + + if (confirm(__("Reset password of selected user?"))) { + notify_progress("Resetting password for selected user..."); + + const id = rows[0]; + + xhrPost("backend.php", {op: "pref-users", method: "resetPass", id: id}, (transport) => { + notify(''); + alert(transport.responseText); + }); + + } + }, + removeSelected: function() { + const sel_rows = this.getSelection(); + + if (sel_rows.length > 0) { + if (confirm(__("Remove selected users? Neither default admin nor your account will be removed."))) { + notify_progress("Removing selected users..."); + + const query = { + op: "pref-users", method: "remove", + ids: sel_rows.toString() + }; + + xhrPost("backend.php", query, () => { + this.reload(); + }); + } + + } else { + alert(__("No users selected.")); + } + }, + editSelected: function() { + const rows = this.getSelection(); + + if (rows.length == 0) { + alert(__("No users selected.")); + return; + } + + if (rows.length > 1) { + alert(__("Please select one user.")); + return; + } + + this.edit(rows[0]); + }, + getSelection :function() { + return Tables.getSelected("prefUserList"); + } + }); +}); + + diff --git a/js/Utils.js b/js/Utils.js new file mode 100644 index 000000000..204b3189c --- /dev/null +++ b/js/Utils.js @@ -0,0 +1,338 @@ +define(["dojo/_base/declare"], function (declare) { + return declare("fox.Utils", null, { + _rpc_seq: 0, + hotkey_prefix: 0, + hotkey_prefix_pressed: false, + hotkey_prefix_timeout: 0, + urlParam: function(param) { + return String(window.location.href).parseQuery()[param]; + }, + next_seq: function() { + this._rpc_seq += 1; + return this._rpc_seq; + }, + get_seq: function() { + return this._rpc_seq; + }, + setLoadingProgress: function(p) { + loading_progress += p; + + if (dijit.byId("loading_bar")) + dijit.byId("loading_bar").update({progress: loading_progress}); + + if (loading_progress >= 90) + Element.hide("overlay"); + + }, + keyeventToAction: function(event) { + + const hotkeys_map = getInitParam("hotkeys"); + const keycode = event.which; + const keychar = String.fromCharCode(keycode).toLowerCase(); + + if (keycode == 27) { // escape and drop prefix + this.hotkey_prefix = false; + } + + if (keycode == 16 || keycode == 17) return; // ignore lone shift / ctrl + + if (!this.hotkey_prefix && hotkeys_map[0].indexOf(keychar) != -1) { + + this.hotkey_prefix = keychar; + $("cmdline").innerHTML = keychar; + Element.show("cmdline"); + + window.clearTimeout(this.hotkey_prefix_timeout); + this.hotkey_prefix_timeout = window.setTimeout(() => { + this.hotkey_prefix = false; + Element.hide("cmdline"); + }, 3 * 1000); + + event.stopPropagation(); + + return false; + } + + Element.hide("cmdline"); + + let hotkey_name = keychar.search(/[a-zA-Z0-9]/) != -1 ? keychar : "(" + keycode + ")"; + + // ensure ^*char notation + if (event.shiftKey) hotkey_name = "*" + hotkey_name; + if (event.ctrlKey) hotkey_name = "^" + hotkey_name; + if (event.altKey) hotkey_name = "+" + hotkey_name; + if (event.metaKey) hotkey_name = "%" + hotkey_name; + + const hotkey_full = this.hotkey_prefix ? this.hotkey_prefix + " " + hotkey_name : hotkey_name; + this.hotkey_prefix = false; + + let action_name = false; + + for (const sequence in hotkeys_map[1]) { + if (hotkeys_map[1].hasOwnProperty(sequence)) { + if (sequence == hotkey_full) { + action_name = hotkeys_map[1][sequence]; + break; + } + } + } + + console.log('keyeventToAction', hotkey_full, '=>', action_name); + + return action_name; + }, + cleanupMemory: function(root) { + const dijits = dojo.query("[widgetid]", dijit.byId(root).domNode).map(dijit.byNode); + + dijits.each(function (d) { + dojo.destroy(d.domNode); + }); + + $$("#" + root + " *").each(function (i) { + i.parentNode ? i.parentNode.removeChild(i) : true; + }); + }, + helpDialog: function(topic) { + const query = "backend.php?op=backend&method=help&topic=" + param_escape(topic); + + if (dijit.byId("helpDlg")) + dijit.byId("helpDlg").destroyRecursive(); + + const dialog = new dijit.Dialog({ + id: "helpDlg", + title: __("Help"), + style: "width: 600px", + href: query, + }); + + dialog.show(); + }, + displayDlg: function(title, id, param, callback) { + notify_progress("Loading, please wait...", true); + + const query = {op: "dlg", method: id, param: param}; + + xhrPost("backend.php", query, (transport) => { + try { + const content = transport.responseText; + + let dialog = dijit.byId("infoBox"); + + if (!dialog) { + dialog = new dijit.Dialog({ + title: title, + id: 'infoBox', + style: "width: 600px", + onCancel: function () { + return true; + }, + onExecute: function () { + return true; + }, + onClose: function () { + return true; + }, + content: content + }); + } else { + dialog.attr('title', title); + dialog.attr('content', content); + } + + dialog.show(); + + notify(""); + + if (callback) callback(transport); + } catch (e) { + exception_error(e); + } + }); + + return false; + }, + handleRpcJson: function(transport) { + + const netalert_dijit = dijit.byId("net-alert"); + let netalert = false; + + if (netalert_dijit) netalert = netalert_dijit.domNode; + + try { + const reply = JSON.parse(transport.responseText); + + if (reply) { + + const error = reply['error']; + + if (error) { + const code = error['code']; + const msg = error['msg']; + + console.warn("[handleRpcJson] received fatal error " + code + "/" + msg); + + if (code != 0) { + fatalError(code, msg); + return false; + } + } + + const seq = reply['seq']; + + if (seq && this.get_seq() != seq) { + console.log("[handleRpcJson] sequence mismatch: " + seq + + " (want: " + this.get_seq() + ")"); + return true; + } + + const message = reply['message']; + + if (message == "UPDATE_COUNTERS") { + console.log("need to refresh counters..."); + setInitParam("last_article_id", -1); + Feeds.requestCounters(true); + } + + const counters = reply['counters']; + + if (counters) + Feeds.parseCounters(counters); + + const runtime_info = reply['runtime-info']; + + if (runtime_info) + Utils.parseRuntimeInfo(runtime_info); + + if (netalert) netalert.hide(); + + return reply; + + } else { + if (netalert) + netalert.show(); + else + notify_error("Communication problem with server."); + } + + } catch (e) { + if (netalert) + netalert.show(); + else + notify_error("Communication problem with server."); + + console.error(e); + } + + return false; + }, + parseRuntimeInfo: function(data) { + + //console.log("parsing runtime info..."); + + for (const k in data) { + if (data.hasOwnProperty(k)) { + const v = data[k]; + + console.log("RI:", k, "=>", v); + + if (k == "dep_ts" && parseInt(getInitParam("dep_ts")) > 0) { + if (parseInt(getInitParam("dep_ts")) < parseInt(v) && getInitParam("reload_on_ts_change")) { + window.location.reload(); + } + } + + if (k == "daemon_is_running" && v != 1) { + notify_error("Update daemon is not running.", true); + return; + } + + if (k == "update_result") { + const updatesIcon = dijit.byId("updatesIcon").domNode; + + if (v) { + Element.show(updatesIcon); + } else { + Element.hide(updatesIcon); + } + } + + if (k == "daemon_stamp_ok" && v != 1) { + notify_error("Update daemon is not updating feeds.", true); + return; + } + + if (k == "max_feed_id" || k == "num_feeds") { + if (init_params[k] != v) { + console.log("feed count changed, need to reload feedlist."); + Feeds.reload(); + } + } + + init_params[k] = v; + } + } + + PluginHost.run(PluginHost.HOOK_RUNTIME_INFO_LOADED, data); + }, + backendSanityCallback: function (transport) { + + const reply = JSON.parse(transport.responseText); + + if (!reply) { + fatalError(3, "Sanity check: invalid RPC reply", transport.responseText); + return; + } + + const error_code = reply['error']['code']; + + if (error_code && error_code != 0) { + return fatalError(error_code, reply['error']['message']); + } + + console.log("sanity check ok"); + + const params = reply['init-params']; + + if (params) { + console.log('reading init-params...'); + + for (const k in params) { + if (params.hasOwnProperty(k)) { + switch (k) { + case "label_base_index": + _label_base_index = parseInt(params[k]); + break; + case "hotkeys": + // filter mnemonic definitions (used for help panel) from hotkeys map + // i.e. *(191)|Ctrl-/ -> *(191) + + const tmp = []; + for (const sequence in params[k][1]) { + if (params[k][1].hasOwnProperty(sequence)) { + const filtered = sequence.replace(/\|.*$/, ""); + tmp[filtered] = params[k][1][sequence]; + } + } + + params[k][1] = tmp; + break; + } + + console.log("IP:", k, "=>", params[k]); + } + } + + init_params = params; + + // PluginHost might not be available on non-index pages + window.PluginHost && PluginHost.run(PluginHost.HOOK_PARAMS_LOADED, init_params); + } + + App.initSecondStage(); + }, + explainError: function(code) { + return this.displayDlg(__("Error explained"), "explainError", code); + }, + + }); +}); diff --git a/js/functions.js b/js/functions.js index 3118da0f0..0d52358ec 100755 --- a/js/functions.js +++ b/js/functions.js @@ -112,733 +112,6 @@ const Tables = { } }; -const Utils = { - _rpc_seq: 0, - hotkey_prefix: 0, - hotkey_prefix_pressed: false, - hotkey_prefix_timeout: 0, - urlParam: function(param) { - return String(window.location.href).parseQuery()[param]; - }, - next_seq: function() { - this._rpc_seq += 1; - return this._rpc_seq; - }, - get_seq: function() { - return this._rpc_seq; - }, - setLoadingProgress: function(p) { - loading_progress += p; - - if (dijit.byId("loading_bar")) - dijit.byId("loading_bar").update({progress: loading_progress}); - - if (loading_progress >= 90) - Element.hide("overlay"); - - }, - keyeventToAction: function(event) { - - const hotkeys_map = getInitParam("hotkeys"); - const keycode = event.which; - const keychar = String.fromCharCode(keycode).toLowerCase(); - - if (keycode == 27) { // escape and drop prefix - this.hotkey_prefix = false; - } - - if (keycode == 16 || keycode == 17) return; // ignore lone shift / ctrl - - if (!this.hotkey_prefix && hotkeys_map[0].indexOf(keychar) != -1) { - - this.hotkey_prefix = keychar; - $("cmdline").innerHTML = keychar; - Element.show("cmdline"); - - window.clearTimeout(this.hotkey_prefix_timeout); - this.hotkey_prefix_timeout = window.setTimeout(() => { - this.hotkey_prefix = false; - Element.hide("cmdline"); - }, 3 * 1000); - - event.stopPropagation(); - - return false; - } - - Element.hide("cmdline"); - - let hotkey_name = keychar.search(/[a-zA-Z0-9]/) != -1 ? keychar : "(" + keycode + ")"; - - // ensure ^*char notation - if (event.shiftKey) hotkey_name = "*" + hotkey_name; - if (event.ctrlKey) hotkey_name = "^" + hotkey_name; - if (event.altKey) hotkey_name = "+" + hotkey_name; - if (event.metaKey) hotkey_name = "%" + hotkey_name; - - const hotkey_full = this.hotkey_prefix ? this.hotkey_prefix + " " + hotkey_name : hotkey_name; - this.hotkey_prefix = false; - - let action_name = false; - - for (const sequence in hotkeys_map[1]) { - if (hotkeys_map[1].hasOwnProperty(sequence)) { - if (sequence == hotkey_full) { - action_name = hotkeys_map[1][sequence]; - break; - } - } - } - - console.log('keyeventToAction', hotkey_full, '=>', action_name); - - return action_name; - }, - cleanupMemory: function(root) { - const dijits = dojo.query("[widgetid]", dijit.byId(root).domNode).map(dijit.byNode); - - dijits.each(function (d) { - dojo.destroy(d.domNode); - }); - - $$("#" + root + " *").each(function (i) { - i.parentNode ? i.parentNode.removeChild(i) : true; - }); - }, - helpDialog: function(topic) { - const query = "backend.php?op=backend&method=help&topic=" + param_escape(topic); - - if (dijit.byId("helpDlg")) - dijit.byId("helpDlg").destroyRecursive(); - - const dialog = new dijit.Dialog({ - id: "helpDlg", - title: __("Help"), - style: "width: 600px", - href: query, - }); - - dialog.show(); - }, - displayDlg: function(title, id, param, callback) { - notify_progress("Loading, please wait...", true); - - const query = {op: "dlg", method: id, param: param}; - - xhrPost("backend.php", query, (transport) => { - try { - const content = transport.responseText; - - let dialog = dijit.byId("infoBox"); - - if (!dialog) { - dialog = new dijit.Dialog({ - title: title, - id: 'infoBox', - style: "width: 600px", - onCancel: function () { - return true; - }, - onExecute: function () { - return true; - }, - onClose: function () { - return true; - }, - content: content - }); - } else { - dialog.attr('title', title); - dialog.attr('content', content); - } - - dialog.show(); - - notify(""); - - if (callback) callback(transport); - } catch (e) { - exception_error(e); - } - }); - - return false; - }, - handleRpcJson: function(transport) { - - const netalert_dijit = dijit.byId("net-alert"); - let netalert = false; - - if (netalert_dijit) netalert = netalert_dijit.domNode; - - try { - const reply = JSON.parse(transport.responseText); - - if (reply) { - - const error = reply['error']; - - if (error) { - const code = error['code']; - const msg = error['msg']; - - console.warn("[handleRpcJson] received fatal error " + code + "/" + msg); - - if (code != 0) { - fatalError(code, msg); - return false; - } - } - - const seq = reply['seq']; - - if (seq && this.get_seq() != seq) { - console.log("[handleRpcJson] sequence mismatch: " + seq + - " (want: " + this.get_seq() + ")"); - return true; - } - - const message = reply['message']; - - if (message == "UPDATE_COUNTERS") { - console.log("need to refresh counters..."); - setInitParam("last_article_id", -1); - Feeds.requestCounters(true); - } - - const counters = reply['counters']; - - if (counters) - Feeds.parseCounters(counters); - - const runtime_info = reply['runtime-info']; - - if (runtime_info) - Utils.parseRuntimeInfo(runtime_info); - - if (netalert) netalert.hide(); - - return reply; - - } else { - if (netalert) - netalert.show(); - else - notify_error("Communication problem with server."); - } - - } catch (e) { - if (netalert) - netalert.show(); - else - notify_error("Communication problem with server."); - - console.error(e); - } - - return false; - }, - parseRuntimeInfo: function(data) { - - //console.log("parsing runtime info..."); - - for (const k in data) { - if (data.hasOwnProperty(k)) { - const v = data[k]; - - console.log("RI:", k, "=>", v); - - if (k == "dep_ts" && parseInt(getInitParam("dep_ts")) > 0) { - if (parseInt(getInitParam("dep_ts")) < parseInt(v) && getInitParam("reload_on_ts_change")) { - window.location.reload(); - } - } - - if (k == "daemon_is_running" && v != 1) { - notify_error("Update daemon is not running.", true); - return; - } - - if (k == "update_result") { - const updatesIcon = dijit.byId("updatesIcon").domNode; - - if (v) { - Element.show(updatesIcon); - } else { - Element.hide(updatesIcon); - } - } - - if (k == "daemon_stamp_ok" && v != 1) { - notify_error("Update daemon is not updating feeds.", true); - return; - } - - if (k == "max_feed_id" || k == "num_feeds") { - if (init_params[k] != v) { - console.log("feed count changed, need to reload feedlist."); - Feeds.reload(); - } - } - - init_params[k] = v; - } - } - - PluginHost.run(PluginHost.HOOK_RUNTIME_INFO_LOADED, data); - }, - backendSanityCallback: function (transport) { - - const reply = JSON.parse(transport.responseText); - - if (!reply) { - fatalError(3, "Sanity check: invalid RPC reply", transport.responseText); - return; - } - - const error_code = reply['error']['code']; - - if (error_code && error_code != 0) { - return fatalError(error_code, reply['error']['message']); - } - - console.log("sanity check ok"); - - const params = reply['init-params']; - - if (params) { - console.log('reading init-params...'); - - for (const k in params) { - if (params.hasOwnProperty(k)) { - switch (k) { - case "label_base_index": - _label_base_index = parseInt(params[k]); - break; - case "hotkeys": - // filter mnemonic definitions (used for help panel) from hotkeys map - // i.e. *(191)|Ctrl-/ -> *(191) - - const tmp = []; - for (const sequence in params[k][1]) { - if (params[k][1].hasOwnProperty(sequence)) { - const filtered = sequence.replace(/\|.*$/, ""); - tmp[filtered] = params[k][1][sequence]; - } - } - - params[k][1] = tmp; - break; - } - - console.log("IP:", k, "=>", params[k]); - } - } - - init_params = params; - - // PluginHost might not be available on non-index pages - window.PluginHost && PluginHost.run(PluginHost.HOOK_PARAMS_LOADED, init_params); - } - - App.initSecondStage(); - }, - explainError: function(code) { - return this.displayDlg(__("Error explained"), "explainError", code); - }, -}; - -const CommonDialogs = { - quickAddFeed: function() { - const query = "backend.php?op=feeds&method=quickAddFeed"; - - // overlapping widgets - if (dijit.byId("batchSubDlg")) dijit.byId("batchSubDlg").destroyRecursive(); - if (dijit.byId("feedAddDlg")) dijit.byId("feedAddDlg").destroyRecursive(); - - const dialog = new dijit.Dialog({ - id: "feedAddDlg", - title: __("Subscribe to Feed"), - style: "width: 600px", - show_error: function (msg) { - const elem = $("fadd_error_message"); - - elem.innerHTML = msg; - - if (!Element.visible(elem)) - new Effect.Appear(elem); - - }, - execute: function () { - if (this.validate()) { - console.log(dojo.objectToQuery(this.attr('value'))); - - const feed_url = this.attr('value').feed; - - Element.show("feed_add_spinner"); - Element.hide("fadd_error_message"); - - xhrPost("backend.php", this.attr('value'), (transport) => { - try { - - try { - var reply = JSON.parse(transport.responseText); - } catch (e) { - Element.hide("feed_add_spinner"); - alert(__("Failed to parse output. This can indicate server timeout and/or network issues. Backend output was logged to browser console.")); - console.log('quickAddFeed, backend returned:' + transport.responseText); - return; - } - - const rc = reply['result']; - - notify(''); - Element.hide("feed_add_spinner"); - - console.log(rc); - - switch (parseInt(rc['code'])) { - case 1: - dialog.hide(); - notify_info(__("Subscribed to %s").replace("%s", feed_url)); - - Feeds.reload(); - break; - case 2: - dialog.show_error(__("Specified URL seems to be invalid.")); - break; - case 3: - dialog.show_error(__("Specified URL doesn't seem to contain any feeds.")); - break; - case 4: - const feeds = rc['feeds']; - - Element.show("fadd_multiple_notify"); - - const select = dijit.byId("feedDlg_feedContainerSelect"); - - while (select.getOptions().length > 0) - select.removeOption(0); - - select.addOption({value: '', label: __("Expand to select feed")}); - - let count = 0; - for (const feedUrl in feeds) { - if (feeds.hasOwnProperty(feedUrl)) { - select.addOption({value: feedUrl, label: feeds[feedUrl]}); - count++; - } - } - - Effect.Appear('feedDlg_feedsContainer', {duration: 0.5}); - - break; - case 5: - dialog.show_error(__("Couldn't download the specified URL: %s").replace("%s", rc['message'])); - break; - case 6: - dialog.show_error(__("XML validation failed: %s").replace("%s", rc['message'])); - break; - case 0: - dialog.show_error(__("You are already subscribed to this feed.")); - break; - } - - } catch (e) { - console.error(transport.responseText); - exception_error(e); - } - }); - } - }, - href: query - }); - - dialog.show(); - }, - showFeedsWithErrors: function() { - const query = {op: "pref-feeds", method: "feedsWithErrors"}; - - if (dijit.byId("errorFeedsDlg")) - dijit.byId("errorFeedsDlg").destroyRecursive(); - - const dialog = new dijit.Dialog({ - id: "errorFeedsDlg", - title: __("Feeds with update errors"), - style: "width: 600px", - getSelectedFeeds: function () { - return Tables.getSelected("prefErrorFeedList"); - }, - removeSelected: function () { - const sel_rows = this.getSelectedFeeds(); - - if (sel_rows.length > 0) { - if (confirm(__("Remove selected feeds?"))) { - notify_progress("Removing selected feeds...", true); - - const query = { - op: "pref-feeds", method: "remove", - ids: sel_rows.toString() - }; - - xhrPost("backend.php", query, () => { - notify(''); - dialog.hide(); - Feeds.reload(); - }); - } - - } else { - alert(__("No feeds selected.")); - } - }, - execute: function () { - if (this.validate()) { - // - } - }, - href: "backend.php?" + dojo.objectToQuery(query) - }); - - dialog.show(); - }, - feedBrowser: function() { - const query = {op: "feeds", method: "feedBrowser"}; - - if (dijit.byId("feedAddDlg")) - dijit.byId("feedAddDlg").hide(); - - if (dijit.byId("feedBrowserDlg")) - dijit.byId("feedBrowserDlg").destroyRecursive(); - - // noinspection JSUnusedGlobalSymbols - const dialog = new dijit.Dialog({ - id: "feedBrowserDlg", - title: __("More Feeds"), - style: "width: 600px", - getSelectedFeedIds: function () { - const list = $$("#browseFeedList li[id*=FBROW]"); - const selected = []; - - list.each(function (child) { - const id = child.id.replace("FBROW-", ""); - - if (child.hasClassName('Selected')) { - selected.push(id); - } - }); - - return selected; - }, - getSelectedFeeds: function () { - const list = $$("#browseFeedList li.Selected"); - const selected = []; - - list.each(function (child) { - const title = child.getElementsBySelector("span.fb_feedTitle")[0].innerHTML; - const url = child.getElementsBySelector("a.fb_feedUrl")[0].href; - - selected.push([title, url]); - - }); - - return selected; - }, - - subscribe: function () { - const mode = this.attr('value').mode; - let selected = []; - - if (mode == "1") - selected = this.getSelectedFeeds(); - else - selected = this.getSelectedFeedIds(); - - if (selected.length > 0) { - dijit.byId("feedBrowserDlg").hide(); - - notify_progress("Loading, please wait...", true); - - const query = { - op: "rpc", method: "massSubscribe", - payload: JSON.stringify(selected), mode: mode - }; - - xhrPost("backend.php", query, () => { - notify(''); - Feeds.reload(); - }); - - } else { - alert(__("No feeds selected.")); - } - - }, - update: function () { - Element.show('feed_browser_spinner'); - - xhrPost("backend.php", dialog.attr("value"), (transport) => { - notify(''); - - Element.hide('feed_browser_spinner'); - - const reply = JSON.parse(transport.responseText); - const mode = reply['mode']; - - if ($("browseFeedList") && reply['content']) { - $("browseFeedList").innerHTML = reply['content']; - } - - dojo.parser.parse("browseFeedList"); - - if (mode == 2) { - Element.show(dijit.byId('feed_archive_remove').domNode); - } else { - Element.hide(dijit.byId('feed_archive_remove').domNode); - } - }); - }, - removeFromArchive: function () { - const selected = this.getSelectedFeedIds(); - - if (selected.length > 0) { - if (confirm(__("Remove selected feeds from the archive? Feeds with stored articles will not be removed."))) { - Element.show('feed_browser_spinner'); - - const query = {op: "rpc", method: "remarchive", ids: selected.toString()}; - - xhrPost("backend.php", query, () => { - dialog.update(); - }); - } - } - }, - execute: function () { - if (this.validate()) { - this.subscribe(); - } - }, - href: "backend.php?" + dojo.objectToQuery(query) - }); - - dialog.show(); - }, - addLabel: function(select, callback) { - const caption = prompt(__("Please enter label caption:"), ""); - - if (caption != undefined && caption.trim().length > 0) { - - const query = {op: "pref-labels", method: "add", caption: caption.trim()}; - - if (select) - Object.extend(query, {output: "select"}); - - notify_progress("Loading, please wait...", true); - - xhrPost("backend.php", query, (transport) => { - if (callback) { - callback(transport); - } else if (App.isPrefs()) { - dijit.byId("labelTree").reload(); - } else { - Feeds.reload(); - } - }); - } - }, - unsubscribeFeed: function(feed_id, title) { - - const msg = __("Unsubscribe from %s?").replace("%s", title); - - if (title == undefined || confirm(msg)) { - notify_progress("Removing feed..."); - - const query = {op: "pref-feeds", quiet: 1, method: "remove", ids: feed_id}; - - xhrPost("backend.php", query, () => { - if (dijit.byId("feedEditDlg")) dijit.byId("feedEditDlg").hide(); - - if (App.isPrefs()) { - Feeds.reload(); - } else { - if (feed_id == Feeds.getActive()) - setTimeout(() => { - Feeds.open({feed: -5}) - }, - 100); - - if (feed_id < 0) Feeds.reload(); - } - }); - } - - return false; - }, - editFeed: function (feed) { - if (feed <= 0) - return alert(__("You can't edit this kind of feed.")); - - const query = {op: "pref-feeds", method: "editfeed", id: feed}; - - console.log("editFeed", query); - - if (dijit.byId("filterEditDlg")) - dijit.byId("filterEditDlg").destroyRecursive(); - - if (dijit.byId("feedEditDlg")) - dijit.byId("feedEditDlg").destroyRecursive(); - - const dialog = new dijit.Dialog({ - id: "feedEditDlg", - title: __("Edit Feed"), - style: "width: 600px", - execute: function () { - if (this.validate()) { - notify_progress("Saving data...", true); - - xhrPost("backend.php", dialog.attr('value'), () => { - dialog.hide(); - notify(''); - Feeds.reload(); - }); - } - }, - href: "backend.php?" + dojo.objectToQuery(query) - }); - - dialog.show(); - }, - genUrlChangeKey: function(feed, is_cat) { - if (confirm(__("Generate new syndication address for this feed?"))) { - - notify_progress("Trying to change address...", true); - - const query = {op: "pref-feeds", method: "regenFeedKey", id: feed, is_cat: is_cat}; - - xhrJson("backend.php", query, (reply) => { - const new_link = reply.link; - const e = $('gen_feed_url'); - - if (new_link) { - e.innerHTML = e.innerHTML.replace(/&key=.*$/, - "&key=" + new_link); - - e.href = e.href.replace(/&key=.*$/, - "&key=" + new_link); - - new Effect.Highlight(e); - - notify(''); - - } else { - notify_error("Could not change feed URL."); - } - }); - } - return false; - } -}; - function report_error(message, filename, lineno, colno, error) { exception_error(error, null, filename, lineno); } @@ -1109,395 +382,6 @@ function fatalError(code, msg, ext_info) { } -const Filters = { - filterDlgCheckAction: function(sender) { - const action = sender.value; - - const action_param = $("filterDlg_paramBox"); - - if (!action_param) { - console.log("filterDlgCheckAction: can't find action param box!"); - return; - } - - // if selected action supports parameters, enable params field - if (action == 4 || action == 6 || action == 7 || action == 9) { - new Effect.Appear(action_param, {duration: 0.5}); - - Element.hide(dijit.byId("filterDlg_actionParam").domNode); - Element.hide(dijit.byId("filterDlg_actionParamLabel").domNode); - Element.hide(dijit.byId("filterDlg_actionParamPlugin").domNode); - - if (action == 7) { - Element.show(dijit.byId("filterDlg_actionParamLabel").domNode); - } else if (action == 9) { - Element.show(dijit.byId("filterDlg_actionParamPlugin").domNode); - } else { - Element.show(dijit.byId("filterDlg_actionParam").domNode); - } - - } else { - Element.hide(action_param); - } - }, - createNewRuleElement: function(parentNode, replaceNode) { - const form = document.forms["filter_new_rule_form"]; - const query = {op: "pref-filters", method: "printrulename", rule: dojo.formToJson(form)}; - - xhrPost("backend.php", query, (transport) => { - try { - const li = dojo.create("li"); - - const cb = dojo.create("input", {type: "checkbox"}, li); - - new dijit.form.CheckBox({ - onChange: function () { - Lists.onRowChecked(this); - }, - }, cb); - - dojo.create("input", { - type: "hidden", - name: "rule[]", - value: dojo.formToJson(form) - }, li); - - dojo.create("span", { - onclick: function () { - dijit.byId('filterEditDlg').editRule(this); - }, - innerHTML: transport.responseText - }, li); - - if (replaceNode) { - parentNode.replaceChild(li, replaceNode); - } else { - parentNode.appendChild(li); - } - } catch (e) { - exception_error(e); - } - }); - }, - createNewActionElement: function(parentNode, replaceNode) { - const form = document.forms["filter_new_action_form"]; - - if (form.action_id.value == 7) { - form.action_param.value = form.action_param_label.value; - } else if (form.action_id.value == 9) { - form.action_param.value = form.action_param_plugin.value; - } - - const query = { - op: "pref-filters", method: "printactionname", - action: dojo.formToJson(form) - }; - - xhrPost("backend.php", query, (transport) => { - try { - const li = dojo.create("li"); - - const cb = dojo.create("input", {type: "checkbox"}, li); - - new dijit.form.CheckBox({ - onChange: function () { - Lists.onRowChecked(this); - }, - }, cb); - - dojo.create("input", { - type: "hidden", - name: "action[]", - value: dojo.formToJson(form) - }, li); - - dojo.create("span", { - onclick: function () { - dijit.byId('filterEditDlg').editAction(this); - }, - innerHTML: transport.responseText - }, li); - - if (replaceNode) { - parentNode.replaceChild(li, replaceNode); - } else { - parentNode.appendChild(li); - } - - } catch (e) { - exception_error(e); - } - }); - }, - addFilterRule: function(replaceNode, ruleStr) { - if (dijit.byId("filterNewRuleDlg")) - dijit.byId("filterNewRuleDlg").destroyRecursive(); - - const query = "backend.php?op=pref-filters&method=newrule&rule=" + - param_escape(ruleStr); - - const rule_dlg = new dijit.Dialog({ - id: "filterNewRuleDlg", - title: ruleStr ? __("Edit rule") : __("Add rule"), - style: "width: 600px", - execute: function () { - if (this.validate()) { - Filters.createNewRuleElement($("filterDlg_Matches"), replaceNode); - this.hide(); - } - }, - href: query - }); - - rule_dlg.show(); - }, - addFilterAction: function(replaceNode, actionStr) { - if (dijit.byId("filterNewActionDlg")) - dijit.byId("filterNewActionDlg").destroyRecursive(); - - const query = "backend.php?op=pref-filters&method=newaction&action=" + - param_escape(actionStr); - - const rule_dlg = new dijit.Dialog({ - id: "filterNewActionDlg", - title: actionStr ? __("Edit action") : __("Add action"), - style: "width: 600px", - execute: function () { - if (this.validate()) { - Filters.createNewActionElement($("filterDlg_Actions"), replaceNode); - this.hide(); - } - }, - href: query - }); - - rule_dlg.show(); - }, - editFilterTest: function(query) { - - if (dijit.byId("filterTestDlg")) - dijit.byId("filterTestDlg").destroyRecursive(); - - const test_dlg = new dijit.Dialog({ - id: "filterTestDlg", - title: "Test Filter", - style: "width: 600px", - results: 0, - limit: 100, - max_offset: 10000, - getTestResults: function (query, offset) { - const updquery = query + "&offset=" + offset + "&limit=" + test_dlg.limit; - - console.log("getTestResults:" + offset); - - xhrPost("backend.php", updquery, (transport) => { - try { - const result = JSON.parse(transport.responseText); - - if (result && dijit.byId("filterTestDlg") && dijit.byId("filterTestDlg").open) { - test_dlg.results += result.length; - - console.log("got results:" + result.length); - - $("prefFilterProgressMsg").innerHTML = __("Looking for articles (%d processed, %f found)...") - .replace("%f", test_dlg.results) - .replace("%d", offset); - - console.log(offset + " " + test_dlg.max_offset); - - for (let i = 0; i < result.length; i++) { - const tmp = new Element("table"); - tmp.innerHTML = result[i]; - dojo.parser.parse(tmp); - - $("prefFilterTestResultList").innerHTML += tmp.innerHTML; - } - - if (test_dlg.results < 30 && offset < test_dlg.max_offset) { - - // get the next batch - window.setTimeout(function () { - test_dlg.getTestResults(query, offset + test_dlg.limit); - }, 0); - - } else { - // all done - - Element.hide("prefFilterLoadingIndicator"); - - if (test_dlg.results == 0) { - $("prefFilterTestResultList").innerHTML = "No recent articles matching this filter have been found."; - $("prefFilterProgressMsg").innerHTML = "Articles matching this filter:"; - } else { - $("prefFilterProgressMsg").innerHTML = __("Found %d articles matching this filter:") - .replace("%d", test_dlg.results); - } - - } - - } else if (!result) { - console.log("getTestResults: can't parse results object"); - - Element.hide("prefFilterLoadingIndicator"); - - notify_error("Error while trying to get filter test results."); - - } else { - console.log("getTestResults: dialog closed, bailing out."); - } - } catch (e) { - exception_error(e); - } - - }); - }, - href: query - }); - - dojo.connect(test_dlg, "onLoad", null, function (e) { - test_dlg.getTestResults(query, 0); - }); - - test_dlg.show(); - }, - quickAddFilter: function() { - let query; - - if (!App.isPrefs()) { - query = { - op: "pref-filters", method: "newfilter", - feed: Feeds.getActive(), is_cat: Feeds.activeIsCat() - }; - } else { - query = {op: "pref-filters", method: "newfilter"}; - } - - console.log('quickAddFilter', query); - - if (dijit.byId("feedEditDlg")) - dijit.byId("feedEditDlg").destroyRecursive(); - - if (dijit.byId("filterEditDlg")) - dijit.byId("filterEditDlg").destroyRecursive(); - - const dialog = new dijit.Dialog({ - id: "filterEditDlg", - title: __("Create Filter"), - style: "width: 600px", - test: function () { - const query = "backend.php?" + dojo.formToQuery("filter_new_form") + "&savemode=test"; - - Filters.editFilterTest(query); - }, - selectRules: function (select) { - $$("#filterDlg_Matches input[type=checkbox]").each(function (e) { - e.checked = select; - if (select) - e.parentNode.addClassName("Selected"); - else - e.parentNode.removeClassName("Selected"); - }); - }, - selectActions: function (select) { - $$("#filterDlg_Actions input[type=checkbox]").each(function (e) { - e.checked = select; - - if (select) - e.parentNode.addClassName("Selected"); - else - e.parentNode.removeClassName("Selected"); - - }); - }, - editRule: function (e) { - const li = e.parentNode; - const rule = li.getElementsByTagName("INPUT")[1].value; - Filters.addFilterRule(li, rule); - }, - editAction: function (e) { - const li = e.parentNode; - const action = li.getElementsByTagName("INPUT")[1].value; - Filters.addFilterAction(li, action); - }, - addAction: function () { - Filters.addFilterAction(); - }, - addRule: function () { - Filters.addFilterRule(); - }, - deleteAction: function () { - $$("#filterDlg_Actions li[class*=Selected]").each(function (e) { - e.parentNode.removeChild(e) - }); - }, - deleteRule: function () { - $$("#filterDlg_Matches li[class*=Selected]").each(function (e) { - e.parentNode.removeChild(e) - }); - }, - execute: function () { - if (this.validate()) { - - const query = dojo.formToQuery("filter_new_form"); - - xhrPost("backend.php", query, () => { - if (App.isPrefs()) { - dijit.byId("filterTree").reload(); - } - - dialog.hide(); - }); - } - }, - href: "backend.php?" + dojo.objectToQuery(query) - }); - - if (!App.isPrefs()) { - const selectedText = getSelectionText(); - - const lh = dojo.connect(dialog, "onLoad", function () { - dojo.disconnect(lh); - - if (selectedText != "") { - - const feed_id = Feeds.activeIsCat() ? 'CAT:' + parseInt(Feeds.getActive()) : - Feeds.getActive(); - - const rule = {reg_exp: selectedText, feed_id: [feed_id], filter_type: 1}; - - Filters.addFilterRule(null, dojo.toJson(rule)); - - } else { - - const query = {op: "rpc", method: "getlinktitlebyid", id: Article.getActive()}; - - xhrPost("backend.php", query, (transport) => { - const reply = JSON.parse(transport.responseText); - - let title = false; - - if (reply && reply.title) title = reply.title; - - if (title || Feeds.getActive() || Feeds.activeIsCat()) { - - console.log(title + " " + Feeds.getActive()); - - const feed_id = Feeds.activeIsCat() ? 'CAT:' + parseInt(Feeds.getActive()) : - Feeds.getActive(); - - const rule = {reg_exp: title, feed_id: [feed_id], filter_type: 1}; - - Filters.addFilterRule(null, dojo.toJson(rule)); - } - }); - } - }); - } - - dialog.show(); - }, -}; - /* function strip_tags(s) { return s.replace(/<\/?[^>]+(>|$)/g, ""); } */ diff --git a/js/prefs.js b/js/prefs.js index 3578a7007..8804bdba9 100755 --- a/js/prefs.js +++ b/js/prefs.js @@ -1,4 +1,10 @@ -/* global dijit, __ */ +/* global dijit, __,fox */ + +let Utils; +let CommonDialogs; +let Filters; +let Users; +let Prefs; const App = { init: function() { @@ -39,6 +45,11 @@ const App = { "dojo/data/ItemFileWriteStore", "lib/CheckBoxStoreModel", "lib/CheckBoxTree", + "fox/Utils", + "fox/CommonDialogs", + "fox/CommonFilters", + "fox/PrefUsers", + "fox/PrefHelpers", "fox/PrefFeedStore", "fox/PrefFilterStore", "fox/PrefFeedTree", @@ -47,6 +58,12 @@ const App = { ready(function () { try { + Utils = fox.Utils(); + CommonDialogs = fox.CommonDialogs(); + Filters = fox.CommonFilters(); + Users = fox.PrefUsers(); + Prefs = fox.PrefHelpers(); + parser.parse(); Utils.setLoadingProgress(50); @@ -131,274 +148,6 @@ const App = { } }; -// noinspection JSUnusedGlobalSymbols -const Prefs = { - clearFeedAccessKeys: function() { - if (confirm(__("This will invalidate all previously generated feed URLs. Continue?"))) { - notify_progress("Clearing URLs..."); - - xhrPost("backend.php", {op: "pref-feeds", method: "clearKeys"}, () => { - notify_info("Generated URLs cleared."); - }); - } - - return false; - }, - updateEventLog: function() { - xhrPost("backend.php", { op: "pref-system" }, (transport) => { - dijit.byId('systemConfigTab').attr('content', transport.responseText); - notify(""); - }); - }, - clearEventLog: function() { - if (confirm(__("Clear event log?"))) { - - notify_progress("Loading, please wait..."); - - xhrPost("backend.php", {op: "pref-system", method: "clearLog"}, () => { - this.updateEventLog(); - }); - } - }, - editProfiles: function() { - - if (dijit.byId("profileEditDlg")) - dijit.byId("profileEditDlg").destroyRecursive(); - - const query = "backend.php?op=pref-prefs&method=editPrefProfiles"; - - // noinspection JSUnusedGlobalSymbols - const dialog = new dijit.Dialog({ - id: "profileEditDlg", - title: __("Settings Profiles"), - style: "width: 600px", - getSelectedProfiles: function () { - return Tables.getSelected("prefFeedProfileList"); - }, - removeSelected: function () { - const sel_rows = this.getSelectedProfiles(); - - if (sel_rows.length > 0) { - if (confirm(__("Remove selected profiles? Active and default profiles will not be removed."))) { - notify_progress("Removing selected profiles...", true); - - const query = { - op: "rpc", method: "remprofiles", - ids: sel_rows.toString() - }; - - xhrPost("backend.php", query, () => { - notify(''); - Prefs.editProfiles(); - }); - } - - } else { - alert(__("No profiles selected.")); - } - }, - activateProfile: function () { - const sel_rows = this.getSelectedProfiles(); - - if (sel_rows.length == 1) { - if (confirm(__("Activate selected profile?"))) { - notify_progress("Loading, please wait..."); - - xhrPost("backend.php", {op: "rpc", method: "setprofile", id: sel_rows.toString()}, () => { - window.location.reload(); - }); - } - - } else { - alert(__("Please choose a profile to activate.")); - } - }, - addProfile: function () { - if (this.validate()) { - notify_progress("Creating profile...", true); - - const query = {op: "rpc", method: "addprofile", title: dialog.attr('value').newprofile}; - - xhrPost("backend.php", query, () => { - notify(''); - Prefs.editProfiles(); - }); - - } - }, - execute: function () { - if (this.validate()) { - } - }, - href: query - }); - - dialog.show(); - }, - customizeCSS: function() { - const query = "backend.php?op=pref-prefs&method=customizeCSS"; - - if (dijit.byId("cssEditDlg")) - dijit.byId("cssEditDlg").destroyRecursive(); - - const dialog = new dijit.Dialog({ - id: "cssEditDlg", - title: __("Customize stylesheet"), - style: "width: 600px", - execute: function () { - notify_progress('Saving data...', true); - - xhrPost("backend.php", this.attr('value'), () => { - window.location.reload(); - }); - - }, - href: query - }); - - dialog.show(); - }, - confirmReset: function() { - if (confirm(__("Reset to defaults?"))) { - xhrPost("backend.php", {op: "pref-prefs", method: "resetconfig"}, (transport) => { - Prefs.refresh(); - notify_info(transport.responseText); - }); - } - }, - clearPluginData: function(name) { - if (confirm(__("Clear stored data for this plugin?"))) { - notify_progress("Loading, please wait..."); - - xhrPost("backend.php", {op: "pref-prefs", method: "clearplugindata", name: name}, () => { - Prefs.refresh(); - }); - } - }, - refresh: function() { - xhrPost("backend.php", { op: "pref-prefs" }, (transport) => { - dijit.byId('genConfigTab').attr('content', transport.responseText); - notify(""); - }); - } -}; - -// noinspection JSUnusedGlobalSymbols -const Users = { - reload: function(sort) { - const user_search = $("user_search"); - const search = user_search ? user_search.value : ""; - - xhrPost("backend.php", { op: "pref-users", sort: sort, search: search }, (transport) => { - dijit.byId('userConfigTab').attr('content', transport.responseText); - notify(""); - }); - }, - add: function() { - const login = prompt(__("Please enter username:"), ""); - - if (login) { - notify_progress("Adding user..."); - - xhrPost("backend.php", {op: "pref-users", method: "add", login: login}, (transport) => { - alert(transport.responseText); - Users.reload(); - }); - - } - }, - edit: function(id) { - const query = "backend.php?op=pref-users&method=edit&id=" + - param_escape(id); - - if (dijit.byId("userEditDlg")) - dijit.byId("userEditDlg").destroyRecursive(); - - const dialog = new dijit.Dialog({ - id: "userEditDlg", - title: __("User Editor"), - style: "width: 600px", - execute: function () { - if (this.validate()) { - notify_progress("Saving data...", true); - - xhrPost("backend.php", dojo.formToObject("user_edit_form"), (transport) => { - dialog.hide(); - Users.reload(); - }); - } - }, - href: query - }); - - dialog.show(); - }, - resetSelected: function() { - const rows = this.getSelection(); - - if (rows.length == 0) { - alert(__("No users selected.")); - return; - } - - if (rows.length > 1) { - alert(__("Please select one user.")); - return; - } - - if (confirm(__("Reset password of selected user?"))) { - notify_progress("Resetting password for selected user..."); - - const id = rows[0]; - - xhrPost("backend.php", {op: "pref-users", method: "resetPass", id: id}, (transport) => { - notify(''); - alert(transport.responseText); - }); - - } - }, - removeSelected: function() { - const sel_rows = this.getSelection(); - - if (sel_rows.length > 0) { - if (confirm(__("Remove selected users? Neither default admin nor your account will be removed."))) { - notify_progress("Removing selected users..."); - - const query = { - op: "pref-users", method: "remove", - ids: sel_rows.toString() - }; - - xhrPost("backend.php", query, () => { - this.reload(); - }); - } - - } else { - alert(__("No users selected.")); - } - }, - editSelected: function() { - const rows = this.getSelection(); - - if (rows.length == 0) { - alert(__("No users selected.")); - return; - } - - if (rows.length > 1) { - alert(__("Please select one user.")); - return; - } - - this.edit(rows[0]); - }, - getSelection :function() { - return Tables.getSelected("prefUserList"); - } -}; - function opmlImportComplete(iframe) { if (!iframe.contentDocument.body.innerHTML) return false; diff --git a/js/tt-rss.js b/js/tt-rss.js index 71bb2337a..d0a97a1c0 100644 --- a/js/tt-rss.js +++ b/js/tt-rss.js @@ -1,4 +1,8 @@ -/* global dijit, __ */ +/* global dijit,__,fox */ + +let Utils; +let CommonDialogs; +let Filters; const App = { global_unread: -1, @@ -44,12 +48,19 @@ const App = { "dijit/tree/dndSource", "dijit/tree/ForestStoreModel", "dojo/data/ItemFileWriteStore", + "fox/Utils", + "fox/CommonDialogs", + "fox/CommonFilters", "fox/FeedStoreModel", "fox/FeedTree"], function (dojo, ready, parser) { ready(function () { try { + Utils = fox.Utils(); + CommonDialogs = fox.CommonDialogs(); + Filters = fox.CommonFilters(); + parser.parse(); if (!App.genericSanityCheck()) -- cgit v1.2.3-54-g00ecf From 807ff074540575e6ef8f99ad32b098a816091171 Mon Sep 17 00:00:00 2001 From: Andrew Dolgov Date: Sun, 2 Dec 2018 17:18:59 +0300 Subject: split main objects to dojo modules --- index.php | 2 +- js/Article.js | 335 +++++++++++ js/ArticleCache.js | 25 + js/Feeds.js | 638 +++++++++++++++++++++ js/Headlines.js | 1213 ++++++++++++++++++++++++++++++++++++++++ js/feedlist.js | 638 --------------------- js/prefs.js | 2 +- js/tt-rss.js | 14 +- js/viewfeed.js | 1569 ---------------------------------------------------- 9 files changed, 2226 insertions(+), 2210 deletions(-) create mode 100644 js/Article.js create mode 100644 js/ArticleCache.js create mode 100644 js/Feeds.js create mode 100755 js/Headlines.js delete mode 100644 js/feedlist.js delete mode 100755 js/viewfeed.js (limited to 'js/tt-rss.js') diff --git a/index.php b/index.php index a2d965239..00bf42830 100644 --- a/index.php +++ b/index.php @@ -114,7 +114,7 @@ require({cache:{}}); + + + diff --git a/js/AppBase.js b/js/AppBase.js new file mode 100644 index 000000000..8987d115e --- /dev/null +++ b/js/AppBase.js @@ -0,0 +1,35 @@ +'use strict' +/* global __, ngettext */ +define(["dojo/_base/declare"], function (declare) { + return declare("fox.AppBase", null, { + _initParams: [], + getInitParam: function(k) { + return this._initParams[k]; + }, + setInitParam: function(k, v) { + this._initParams[k] = v; + }, + constructor: function(args) { + // + }, + enableCsrfSupport: function() { + Ajax.Base.prototype.initialize = Ajax.Base.prototype.initialize.wrap( + function (callOriginal, options) { + + if (App.getInitParam("csrf_token") != undefined) { + Object.extend(options, options || { }); + + if (Object.isString(options.parameters)) + options.parameters = options.parameters.toQueryParams(); + else if (Object.isHash(options.parameters)) + options.parameters = options.parameters.toObject(); + + options.parameters["csrf_token"] = App.getInitParam("csrf_token"); + } + + return callOriginal(options); + } + ); + } + }); +}); diff --git a/js/FeedTree.js b/js/FeedTree.js index 4a28bd2b0..37e3de2d1 100755 --- a/js/FeedTree.js +++ b/js/FeedTree.js @@ -123,7 +123,7 @@ define(["dojo/_base/declare", "dojo/dom-construct", "dijit/Tree", "dijit/Menu"], postCreate: function() { this.connect(this.model, "onChange", "updateCounter"); this.connect(this, "_expandNode", function() { - this.hideRead(getInitParam("hide_read_feeds"), getInitParam("hide_read_shows_special")); + this.hideRead(App.getInitParam("hide_read_feeds"), App.getInitParam("hide_read_shows_special")); }); this.inherited(arguments); diff --git a/js/Feeds.js b/js/Feeds.js index 8b6f6a707..d5371779f 100644 --- a/js/Feeds.js +++ b/js/Feeds.js @@ -83,7 +83,7 @@ define(["dojo/_base/declare"], function (declare) { if (id > 0) { if (has_img) { this.setIcon(id, false, - getInitParam("icons_url") + "/" + id + ".ico?" + has_img); + App.getInitParam("icons_url") + "/" + id + ".ico?" + has_img); } else { this.setIcon(id, false, 'images/blank_icon.gif'); } @@ -91,7 +91,7 @@ define(["dojo/_base/declare"], function (declare) { } } - this.hideOrShowFeeds(getInitParam("hide_read_feeds") == 1); + this.hideOrShowFeeds(App.getInitParam("hide_read_feeds") == 1); this._counters_prev = elems; }, reloadCurrent: function(method) { @@ -132,7 +132,7 @@ define(["dojo/_base/declare"], function (declare) { let query = {op: "rpc", method: "getAllCounters", seq: Utils.next_seq()}; if (!force) - query.last_article_id = getInitParam("last_article_id"); + query.last_article_id = App.getInitParam("last_article_id"); xhrPost("backend.php", query, (transport) => { Utils.handleRpcJson(transport); @@ -160,7 +160,7 @@ define(["dojo/_base/declare"], function (declare) { const treeModel = new fox.FeedStoreModel({ store: store, query: { - "type": getInitParam('enable_feed_cats') == 1 ? "category" : "feed" + "type": App.getInitParam('enable_feed_cats') == 1 ? "category" : "feed" }, rootId: "root", rootLabel: "Feeds", @@ -221,9 +221,9 @@ define(["dojo/_base/declare"], function (declare) { this.open({feed: this.getActive(), is_cat: this.activeIsCat()}); } - this.hideOrShowFeeds(getInitParam("hide_read_feeds") == 1); + this.hideOrShowFeeds(App.getInitParam("hide_read_feeds") == 1); - if (getInitParam("is_default_pw")) { + if (App.getInitParam("is_default_pw")) { console.warn("user password is at default value"); const dialog = new dijit.Dialog({ @@ -246,7 +246,7 @@ define(["dojo/_base/declare"], function (declare) { } // bw_limit disables timeout() so we request initial counters separately - if (getInitParam("bw_limit") == "1") { + if (App.getInitParam("bw_limit") == "1") { this.requestCounters(true); } else { setTimeout(() => { @@ -281,18 +281,18 @@ define(["dojo/_base/declare"], function (declare) { if (tree) return tree.selectFeed(feed, is_cat); }, toggleUnread: function() { - const hide = !(getInitParam("hide_read_feeds") == "1"); + const hide = !(App.getInitParam("hide_read_feeds") == "1"); xhrPost("backend.php", {op: "rpc", method: "setpref", key: "HIDE_READ_FEEDS", value: hide}, () => { this.hideOrShowFeeds(hide); - setInitParam("hide_read_feeds", hide); + App.setInitParam("hide_read_feeds", hide); }); }, hideOrShowFeeds: function(hide) { const tree = dijit.byId("feedTree"); if (tree) - return tree.hideRead(hide, getInitParam("hide_read_shows_special")); + return tree.hideRead(hide, App.getInitParam("hide_read_shows_special")); }, open: function(params) { const feed = params.feed; @@ -366,7 +366,7 @@ define(["dojo/_base/declare"], function (declare) { if (viewfeed_debug) { window.open("backend.php?" + dojo.objectToQuery( - Object.assign({debug: 1, csrf_token: getInitParam("csrf_token")}, query) + Object.assign({debug: 1, csrf_token: App.getInitParam("csrf_token")}, query) )); } @@ -389,7 +389,7 @@ define(["dojo/_base/declare"], function (declare) { catchupAll: function() { const str = __("Mark all articles as read?"); - if (getInitParam("confirm_feed_catchup") != 1 || confirm(str)) { + if (App.getInitParam("confirm_feed_catchup") != 1 || confirm(str)) { Notify.progress("Marking all feeds as read..."); @@ -448,7 +448,7 @@ define(["dojo/_base/declare"], function (declare) { str = str.replace("%s", fn) .replace("%w", mark_what); - if (getInitParam("confirm_feed_catchup") == 1 && !confirm(str)) { + if (App.getInitParam("confirm_feed_catchup") == 1 && !confirm(str)) { return; } @@ -463,7 +463,7 @@ define(["dojo/_base/declare"], function (declare) { xhrPost("backend.php", catchup_query, (transport) => { Utils.handleRpcJson(transport); - const show_next_feed = getInitParam("on_catchup_show_next_feed") == "1"; + const show_next_feed = App.getInitParam("on_catchup_show_next_feed") == "1"; if (show_next_feed) { const nuf = this.getNextUnread(feed, is_cat); @@ -486,7 +486,7 @@ define(["dojo/_base/declare"], function (declare) { const str = __("Mark all articles in %s as read?").replace("%s", title); - if (getInitParam("confirm_feed_catchup") != 1 || confirm(str)) { + if (App.getInitParam("confirm_feed_catchup") != 1 || confirm(str)) { const rows = $$("#headlines-frame > div[id*=RROW][data-orig-feed-id='" + id + "']"); diff --git a/js/Headlines.js b/js/Headlines.js index 68dda8d3e..1bcd35896 100755 --- a/js/Headlines.js +++ b/js/Headlines.js @@ -12,13 +12,13 @@ define(["dojo/_base/declare"], function (declare) { if (App.isCombinedMode()) { - if (!in_body && (event.ctrlKey || id == Article.getActive() || getInitParam("cdm_expanded"))) { + if (!in_body && (event.ctrlKey || id == Article.getActive() || App.getInitParam("cdm_expanded"))) { Article.openInNewWindow(id); } Article.setActive(id); - if (!getInitParam("cdm_expanded")) + if (!App.getInitParam("cdm_expanded")) Article.cdmScrollToId(id); return in_body; @@ -81,7 +81,7 @@ define(["dojo/_base/declare"], function (declare) { // set topmost child in the buffer as active, but not if we're at the beginning (to prevent auto marking // first article as read all the time) if ($("headlines-frame").scrollTop != 0 && - getInitParam("cdm_expanded") && getInitParam("cdm_auto_catchup") == 1) { + App.getInitParam("cdm_expanded") && App.getInitParam("cdm_auto_catchup") == 1) { const rows = $$("#headlines-frame > div[id*=RROW]"); @@ -113,7 +113,7 @@ define(["dojo/_base/declare"], function (declare) { } } - if (getInitParam("cdm_auto_catchup") == 1) { + if (App.getInitParam("cdm_auto_catchup") == 1) { let rows = $$("#headlines-frame > div[id*=RROW][class*=Unread]"); @@ -139,7 +139,7 @@ define(["dojo/_base/declare"], function (declare) { console.log("we seem to be at an end"); - if (getInitParam("on_catchup_show_next_feed") == "1") { + if (App.getInitParam("on_catchup_show_next_feed") == "1") { Feeds.openNextUnread(); } } @@ -150,7 +150,7 @@ define(["dojo/_base/declare"], function (declare) { } }, updateFloatingTitle: function(unread_only) { - if (!App.isCombinedMode()/* || !getInitParam("cdm_expanded")*/) return; + if (!App.isCombinedMode()/* || !App.getInitParam("cdm_expanded")*/) return; const hf = $("headlines-frame"); const elems = $$("#headlines-frame > div[id*=RROW]"); @@ -201,7 +201,7 @@ define(["dojo/_base/declare"], function (declare) { } }, unpackVisible: function() { - if (!App.isCombinedMode() || !getInitParam("cdm_expanded")) return; + if (!App.isCombinedMode() || !App.getInitParam("cdm_expanded")) return; const rows = $$("#headlines-frame div[id*=RROW][data-content]"); const threshold = $("headlines-frame").scrollTop + $("headlines-frame").offsetHeight + 600; @@ -714,7 +714,7 @@ define(["dojo/_base/declare"], function (declare) { str = str.replace("%d", rows.length); str = str.replace("%s", fn); - if (getInitParam("confirm_feed_catchup") == 1 && !confirm(str)) { + if (App.getInitParam("confirm_feed_catchup") == 1 && !confirm(str)) { return; } @@ -839,7 +839,7 @@ define(["dojo/_base/declare"], function (declare) { str = str.replace("%d", rows.length); str = str.replace("%s", fn); - if (getInitParam("confirm_feed_catchup") == 1 && !confirm(str)) { + if (App.getInitParam("confirm_feed_catchup") == 1 && !confirm(str)) { return; } @@ -869,7 +869,7 @@ define(["dojo/_base/declare"], function (declare) { str = str.replace("%d", rows.length); str = str.replace("%s", fn); - if (getInitParam("confirm_feed_catchup") == 1 && !confirm(str)) { + if (App.getInitParam("confirm_feed_catchup") == 1 && !confirm(str)) { return; } @@ -952,7 +952,7 @@ define(["dojo/_base/declare"], function (declare) { } else { const msg = ngettext("Mark %d article as read?", "Mark %d articles as read?", ids_to_mark.length).replace("%d", ids_to_mark.length); - if (getInitParam("confirm_feed_catchup") != 1 || confirm(msg)) { + if (App.getInitParam("confirm_feed_catchup") != 1 || confirm(msg)) { for (var i = 0; i < ids_to_mark.length; i++) { var e = $("RROW-" + ids_to_mark[i]); @@ -1090,7 +1090,7 @@ define(["dojo/_base/declare"], function (declare) { })); - const labels = getInitParam("labels"); + const labels = App.getInitParam("labels"); if (labels && labels.length) { diff --git a/js/Utils.js b/js/Utils.js index 1050cf018..d1de08b2c 100644 --- a/js/Utils.js +++ b/js/Utils.js @@ -28,7 +28,7 @@ define(["dojo/_base/declare"], function (declare) { }, keyeventToAction: function(event) { - const hotkeys_map = getInitParam("hotkeys"); + const hotkeys_map = App.getInitParam("hotkeys"); const keycode = event.which; const keychar = String.fromCharCode(keycode).toLowerCase(); @@ -191,7 +191,7 @@ define(["dojo/_base/declare"], function (declare) { if (message == "UPDATE_COUNTERS") { console.log("need to refresh counters..."); - setInitParam("last_article_id", -1); + App.setInitParam("last_article_id", -1); Feeds.requestCounters(true); } @@ -228,9 +228,6 @@ define(["dojo/_base/declare"], function (declare) { return false; }, parseRuntimeInfo: function(data) { - - //console.log("parsing runtime info..."); - for (const k in data) { if (data.hasOwnProperty(k)) { const v = data[k]; @@ -258,13 +255,13 @@ define(["dojo/_base/declare"], function (declare) { } if (k == "max_feed_id" || k == "num_feeds") { - if (init_params[k] != v) { + if (App.getInitParam(k) != v) { console.log("feed count changed, need to reload feedlist."); Feeds.reload(); } } - init_params[k] = v; + App.setInitParam(k, v); } } @@ -315,13 +312,12 @@ define(["dojo/_base/declare"], function (declare) { } console.log("IP:", k, "=>", params[k]); + App.setInitParam(k, params[k]); } } - init_params = params; - // PluginHost might not be available on non-index pages - window.PluginHost && PluginHost.run(PluginHost.HOOK_PARAMS_LOADED, init_params); + window.PluginHost && PluginHost.run(PluginHost.HOOK_PARAMS_LOADED, App._initParams); } App.initSecondStage(); diff --git a/js/common.js b/js/common.js index 1da3e6d1b..de6d13a78 100755 --- a/js/common.js +++ b/js/common.js @@ -1,28 +1,8 @@ 'use strict' /* global dijit, __ */ -let init_params = {}; let _label_base_index = -1024; let loading_progress = 0; -let notify_hide_timerid = false; - -Ajax.Base.prototype.initialize = Ajax.Base.prototype.initialize.wrap( - function (callOriginal, options) { - - if (getInitParam("csrf_token") != undefined) { - Object.extend(options, options || { }); - - if (Object.isString(options.parameters)) - options.parameters = options.parameters.toQueryParams(); - else if (Object.isHash(options.parameters)) - options.parameters = options.parameters.toObject(); - - options.parameters["csrf_token"] = getInitParam("csrf_token"); - } - - return callOriginal(options); - } -); /* xhr shorthand helpers */ @@ -239,15 +219,15 @@ const Notify = { switch (kind) { case this.KIND_INFO: notify.addClassName("notify_info") - icon = getInitParam("icon_information"); + icon = App.getInitParam("icon_information"); break; case this.KIND_ERROR: notify.addClassName("notify_error"); - icon = getInitParam("icon_alert"); + icon = App.getInitParam("icon_alert"); break; case this.KIND_PROGRESS: notify.addClassName("notify_progress"); - icon = getInitParam("icon_indicator_white") + icon = App.getInitParam("icon_indicator_white") break; } @@ -255,7 +235,7 @@ const Notify = { msgfmt += (" ") - .replace("%s", getInitParam("icon_cross")); + .replace("%s", App.getInitParam("icon_cross")); notify.innerHTML = msgfmt; notify.addClassName("visible"); @@ -289,14 +269,6 @@ function displayIfChecked(checkbox, elemId) { } } -function getInitParam(key) { - return init_params[key]; -} - -function setInitParam(key, value) { - init_params[key] = value; -} - function fatalError(code, msg, ext_info) { if (code == 6) { window.location.href = "index.php"; @@ -390,5 +362,5 @@ function popupOpenArticle(id) { "height=900,width=900,resizable=yes,status=no,location=no,menubar=no,directories=no,scrollbars=yes,toolbar=no"); w.opener = null; - w.location = "backend.php?op=article&method=view&mode=raw&html=1&zoom=1&id=" + id + "&csrf_token=" + getInitParam("csrf_token"); + w.location = "backend.php?op=article&method=view&mode=raw&html=1&zoom=1&id=" + id + "&csrf_token=" + App.getInitParam("csrf_token"); } diff --git a/js/prefs.js b/js/prefs.js index a1866f478..75f285b38 100755 --- a/js/prefs.js +++ b/js/prefs.js @@ -1,64 +1,67 @@ 'use strict' /* global dijit, __ */ +let App; let Utils; let CommonDialogs; let Filters; let Users; let Prefs; -const App = { - init: function() { - window.onerror = function (message, filename, lineno, colno, error) { - report_error(message, filename, lineno, colno, error); - }; - - require(["dojo/_base/kernel", - "dojo/ready", - "dojo/parser", - "dojo/_base/loader", - "dojo/_base/html", - "dijit/ColorPalette", - "dijit/Dialog", - "dijit/form/Button", - "dijit/form/CheckBox", - "dijit/form/DropDownButton", - "dijit/form/FilteringSelect", - "dijit/form/MultiSelect", - "dijit/form/Form", - "dijit/form/RadioButton", - "dijit/form/ComboButton", - "dijit/form/Select", - "dijit/form/SimpleTextarea", - "dijit/form/TextBox", - "dijit/form/ValidationTextBox", - "dijit/InlineEditBox", - "dijit/layout/AccordionContainer", - "dijit/layout/AccordionPane", - "dijit/layout/BorderContainer", - "dijit/layout/ContentPane", - "dijit/layout/TabContainer", - "dijit/Menu", - "dijit/ProgressBar", - "dijit/Toolbar", - "dijit/Tree", - "dijit/tree/dndSource", - "dojo/data/ItemFileWriteStore", - "lib/CheckBoxStoreModel", - "lib/CheckBoxTree", - "fox/Utils", - "fox/CommonDialogs", - "fox/CommonFilters", - "fox/PrefUsers", - "fox/PrefHelpers", - "fox/PrefFeedStore", - "fox/PrefFilterStore", - "fox/PrefFeedTree", - "fox/PrefFilterTree", - "fox/PrefLabelTree"], function (dojo, ready, parser) { - - ready(function () { - try { +require(["dojo/_base/kernel", + "dojo/_base/declare", + "dojo/ready", + "dojo/parser", + "fox/AppBase", + "dojo/_base/loader", + "dojo/_base/html", + "dijit/ColorPalette", + "dijit/Dialog", + "dijit/form/Button", + "dijit/form/CheckBox", + "dijit/form/DropDownButton", + "dijit/form/FilteringSelect", + "dijit/form/MultiSelect", + "dijit/form/Form", + "dijit/form/RadioButton", + "dijit/form/ComboButton", + "dijit/form/Select", + "dijit/form/SimpleTextarea", + "dijit/form/TextBox", + "dijit/form/ValidationTextBox", + "dijit/InlineEditBox", + "dijit/layout/AccordionContainer", + "dijit/layout/AccordionPane", + "dijit/layout/BorderContainer", + "dijit/layout/ContentPane", + "dijit/layout/TabContainer", + "dijit/Menu", + "dijit/ProgressBar", + "dijit/Toolbar", + "dijit/Tree", + "dijit/tree/dndSource", + "dojo/data/ItemFileWriteStore", + "lib/CheckBoxStoreModel", + "lib/CheckBoxTree", + "fox/Utils", + "fox/CommonDialogs", + "fox/CommonFilters", + "fox/PrefUsers", + "fox/PrefHelpers", + "fox/PrefFeedStore", + "fox/PrefFilterStore", + "fox/PrefFeedTree", + "fox/PrefFilterTree", + "fox/PrefLabelTree"], function (dojo, declare, ready, parser, AppBase) { + + ready(function () { + try { + const _App = declare("fox.App", AppBase, { + constructor: function() { + window.onerror = function (message, filename, lineno, colno, error) { + report_error(message, filename, lineno, colno, error); + }; + Utils = fox.Utils(); CommonDialogs = fox.CommonDialogs(); Filters = fox.CommonFilters(); @@ -73,81 +76,87 @@ const App = { const params = {op: "rpc", method: "sanityCheck", clientTzOffset: clientTzOffset}; xhrPost("backend.php", params, (transport) => { - Utils.backendSanityCallback(transport); + try { + Utils.backendSanityCallback(transport); + } catch (e) { + exception_error(e); + } }); + }, + initSecondStage: function() { + document.onkeydown = () => { App.hotkeyHandler(event) }; + Utils.setLoadingProgress(50); + Notify.close(); - } catch (e) { - exception_error(e); - } - }); - }); - }, - initSecondStage: function() { - document.onkeydown = () => { App.hotkeyHandler(event) }; - Utils.setLoadingProgress(50); - Notify.close(); - - let tab = Utils.urlParam('tab'); - - if (tab) { - tab = dijit.byId(tab + "Tab"); - if (tab) { - dijit.byId("pref-tabs").selectChild(tab); - - switch (Utils.urlParam('method')) { - case "editfeed": - window.setTimeout(function () { - CommonDialogs.editFeed(Utils.urlParam('methodparam')) - }, 100); - break; - default: - console.warn("initSecondStage, unknown method:", Utils.urlParam("method")); - } - } - } else { - let tab = localStorage.getItem("ttrss:prefs-tab"); + let tab = Utils.urlParam('tab'); + + if (tab) { + tab = dijit.byId(tab + "Tab"); + if (tab) { + dijit.byId("pref-tabs").selectChild(tab); + + switch (Utils.urlParam('method')) { + case "editfeed": + window.setTimeout(function () { + CommonDialogs.editFeed(Utils.urlParam('methodparam')) + }, 100); + break; + default: + console.warn("initSecondStage, unknown method:", Utils.urlParam("method")); + } + } + } else { + let tab = localStorage.getItem("ttrss:prefs-tab"); + + if (tab) { + tab = dijit.byId(tab); + if (tab) { + dijit.byId("pref-tabs").selectChild(tab); + } + } + } + + dojo.connect(dijit.byId("pref-tabs"), "selectChild", function (elem) { + localStorage.setItem("ttrss:prefs-tab", elem.id); + }); - if (tab) { - tab = dijit.byId(tab); - if (tab) { - dijit.byId("pref-tabs").selectChild(tab); + }, + hotkeyHandler: function (event) { + if (event.target.nodeName == "INPUT" || event.target.nodeName == "TEXTAREA") return; + + const action_name = Utils.keyeventToAction(event); + + if (action_name) { + switch (action_name) { + case "feed_subscribe": + CommonDialogs.quickAddFeed(); + return false; + case "create_label": + CommonDialogs.addLabel(); + return false; + case "create_filter": + Filters.quickAddFilter(); + return false; + case "help_dialog": + Utils.helpDialog("main"); + return false; + default: + console.log("unhandled action: " + action_name + "; keycode: " + event.which); + } + } + }, + isPrefs: function() { + return true; } - } - } + }); - dojo.connect(dijit.byId("pref-tabs"), "selectChild", function (elem) { - localStorage.setItem("ttrss:prefs-tab", elem.id); - }); + App = new _App(); - }, - hotkeyHandler: function (event) { - if (event.target.nodeName == "INPUT" || event.target.nodeName == "TEXTAREA") return; - - const action_name = Utils.keyeventToAction(event); - - if (action_name) { - switch (action_name) { - case "feed_subscribe": - CommonDialogs.quickAddFeed(); - return false; - case "create_label": - CommonDialogs.addLabel(); - return false; - case "create_filter": - Filters.quickAddFilter(); - return false; - case "help_dialog": - Utils.helpDialog("main"); - return false; - default: - console.log("unhandled action: " + action_name + "; keycode: " + event.which); - } + } catch (e) { + exception_error(e); } - }, - isPrefs: function() { - return true; - } -}; + }); +}); function opmlImportComplete(iframe) { if (!iframe.contentDocument.body.innerHTML) return false; diff --git a/js/tt-rss.js b/js/tt-rss.js index 481386114..ec52755a1 100644 --- a/js/tt-rss.js +++ b/js/tt-rss.js @@ -1,6 +1,7 @@ 'use strict' /* global dijit,__ */ +let App; let Utils; let CommonDialogs; let Filters; @@ -9,63 +10,63 @@ let Headlines; let Article; let ArticleCache; -const App = { - global_unread: -1, - _widescreen_mode: false, - hotkey_actions: {}, - init: function() { - - window.onerror = function (message, filename, lineno, colno, error) { - report_error(message, filename, lineno, colno, error); - }; - - require(["dojo/_base/kernel", - "dojo/ready", - "dojo/parser", - "dojo/_base/loader", - "dojo/_base/html", - "dojo/query", - "dijit/ProgressBar", - "dijit/ColorPalette", - "dijit/Dialog", - "dijit/form/Button", - "dijit/form/ComboButton", - "dijit/form/CheckBox", - "dijit/form/DropDownButton", - "dijit/form/FilteringSelect", - "dijit/form/Form", - "dijit/form/RadioButton", - "dijit/form/Select", - "dijit/form/MultiSelect", - "dijit/form/SimpleTextarea", - "dijit/form/TextBox", - "dijit/form/ComboBox", - "dijit/form/ValidationTextBox", - "dijit/InlineEditBox", - "dijit/layout/AccordionContainer", - "dijit/layout/BorderContainer", - "dijit/layout/ContentPane", - "dijit/layout/TabContainer", - "dijit/PopupMenuItem", - "dijit/Menu", - "dijit/Toolbar", - "dijit/Tree", - "dijit/tree/dndSource", - "dijit/tree/ForestStoreModel", - "dojo/data/ItemFileWriteStore", - "fox/Utils", - "fox/CommonDialogs", - "fox/CommonFilters", - "fox/Feeds", - "fox/Headlines", - "fox/Article", - "fox/ArticleCache", - "fox/FeedStoreModel", - "fox/FeedTree"], function (dojo, ready, parser) { - - ready(function () { - - try { +require(["dojo/_base/kernel", + "dojo/_base/declare", + "dojo/ready", + "dojo/parser", + "fox/AppBase", + "dojo/_base/loader", + "dojo/_base/html", + "dojo/query", + "dijit/ProgressBar", + "dijit/ColorPalette", + "dijit/Dialog", + "dijit/form/Button", + "dijit/form/ComboButton", + "dijit/form/CheckBox", + "dijit/form/DropDownButton", + "dijit/form/FilteringSelect", + "dijit/form/Form", + "dijit/form/RadioButton", + "dijit/form/Select", + "dijit/form/MultiSelect", + "dijit/form/SimpleTextarea", + "dijit/form/TextBox", + "dijit/form/ComboBox", + "dijit/form/ValidationTextBox", + "dijit/InlineEditBox", + "dijit/layout/AccordionContainer", + "dijit/layout/BorderContainer", + "dijit/layout/ContentPane", + "dijit/layout/TabContainer", + "dijit/PopupMenuItem", + "dijit/Menu", + "dijit/Toolbar", + "dijit/Tree", + "dijit/tree/dndSource", + "dijit/tree/ForestStoreModel", + "dojo/data/ItemFileWriteStore", + "fox/Utils", + "fox/CommonDialogs", + "fox/CommonFilters", + "fox/Feeds", + "fox/Headlines", + "fox/Article", + "fox/ArticleCache", + "fox/FeedStoreModel", + "fox/FeedTree"], function (dojo, declare, ready, parser, AppBase) { + + ready(function () { + try { + const _App = declare("fox.App", AppBase, { + global_unread: -1, + _widescreen_mode: false, + hotkey_actions: {}, + constructor: function () { + window.onerror = function (message, filename, lineno, colno, error) { + report_error(message, filename, lineno, colno, error); + }; + Utils = fox.Utils(); CommonDialogs = fox.CommonDialogs(); Filters = fox.CommonFilters(); @@ -76,11 +77,11 @@ const App = { parser.parse(); - if (!App.genericSanityCheck()) - return false; + if (!this.genericSanityCheck()) + return; Utils.setLoadingProgress(30); - App.initHotkeyActions(); + this.initHotkeyActions(); const a = document.createElement('audio'); const hasAudio = !!a.canPlayType; @@ -99,483 +100,483 @@ const App = { try { Utils.backendSanityCallback(transport); } catch (e) { - console.error(e); + exception_error(e); } }); + }, + initSecondStage: function () { + this.enableCsrfSupport(); - } catch (e) { - exception_error(e); - } + Feeds.reload(); + Article.close(); - }); + if (parseInt(Cookie.get("ttrss_fh_width")) > 0) { + dijit.byId("feeds-holder").domNode.setStyle( + {width: Cookie.get("ttrss_fh_width") + "px"}); + } + dijit.byId("main").resize(); - }); - }, - initSecondStage: function () { - Feeds.reload(); - Article.close(); + dojo.connect(dijit.byId('feeds-holder'), 'resize', + function (args) { + if (args && args.w >= 0) { + Cookie.set("ttrss_fh_width", args.w, App.getInitParam("cookie_lifetime")); + } + }); - if (parseInt(Cookie.get("ttrss_fh_width")) > 0) { - dijit.byId("feeds-holder").domNode.setStyle( - {width: Cookie.get("ttrss_fh_width") + "px"}); - } + dojo.connect(dijit.byId('content-insert'), 'resize', + function (args) { + if (args && args.w >= 0 && args.h >= 0) { + Cookie.set("ttrss_ci_width", args.w, App.getInitParam("cookie_lifetime")); + Cookie.set("ttrss_ci_height", args.h, App.getInitParam("cookie_lifetime")); + } + }); - dijit.byId("main").resize(); + Cookie.delete("ttrss_test"); - dojo.connect(dijit.byId('feeds-holder'), 'resize', - function (args) { - if (args && args.w >= 0) { - Cookie.set("ttrss_fh_width", args.w, getInitParam("cookie_lifetime")); - } - }); + const toolbar = document.forms["main_toolbar_form"]; - dojo.connect(dijit.byId('content-insert'), 'resize', - function (args) { - if (args && args.w >= 0 && args.h >= 0) { - Cookie.set("ttrss_ci_width", args.w, getInitParam("cookie_lifetime")); - Cookie.set("ttrss_ci_height", args.h, getInitParam("cookie_lifetime")); - } - }); + dijit.getEnclosingWidget(toolbar.view_mode).attr('value', + App.getInitParam("default_view_mode")); - Cookie.delete("ttrss_test"); + dijit.getEnclosingWidget(toolbar.order_by).attr('value', + App.getInitParam("default_view_order_by")); - const toolbar = document.forms["main_toolbar_form"]; + const hash_feed_id = hash_get('f'); + const hash_feed_is_cat = hash_get('c') == "1"; - dijit.getEnclosingWidget(toolbar.view_mode).attr('value', - getInitParam("default_view_mode")); + if (hash_feed_id != undefined) { + Feeds.setActive(hash_feed_id, hash_feed_is_cat); + } - dijit.getEnclosingWidget(toolbar.order_by).attr('value', - getInitParam("default_view_order_by")); + Utils.setLoadingProgress(50); - const hash_feed_id = hash_get('f'); - const hash_feed_is_cat = hash_get('c') == "1"; + ArticleCache.clear(); - if (hash_feed_id != undefined) { - Feeds.setActive(hash_feed_id, hash_feed_is_cat); - } + this._widescreen_mode = App.getInitParam("widescreen"); + this.switchPanelMode(this._widescreen_mode); - Utils.setLoadingProgress(50); + Headlines.initScrollHandler(); - ArticleCache.clear(); + if (App.getInitParam("simple_update")) { + console.log("scheduling simple feed updater..."); + window.setInterval(() => { Feeds.updateRandom() }, 30 * 1000); + } - this._widescreen_mode = getInitParam("widescreen"); - this.switchPanelMode(this._widescreen_mode); + console.log("second stage ok"); + }, + genericSanityCheck: function() { + Cookie.set("ttrss_test", "TEST"); - Headlines.initScrollHandler(); + if (Cookie.get("ttrss_test") != "TEST") { + return fatalError(2); + } - if (getInitParam("simple_update")) { - console.log("scheduling simple feed updater..."); - window.setInterval(() => { Feeds.updateRandom() }, 30 * 1000); - } + return true; + }, + updateTitle: function() { + let tmp = "Tiny Tiny RSS"; - console.log("second stage ok"); - }, - genericSanityCheck: function() { - Cookie.set("ttrss_test", "TEST"); + if (this.global_unread > 0) { + tmp = "(" + this.global_unread + ") " + tmp; + } - if (Cookie.get("ttrss_test") != "TEST") { - return fatalError(2); - } + document.title = tmp; + }, + onViewModeChanged: function() { + ArticleCache.clear(); + return Feeds.reloadCurrent(''); + }, + isCombinedMode: function() { + return App.getInitParam("combined_display_mode"); + }, + hotkeyHandler(event) { + if (event.target.nodeName == "INPUT" || event.target.nodeName == "TEXTAREA") return; + + const action_name = Utils.keyeventToAction(event); + + if (action_name) { + const action_func = this.hotkey_actions[action_name]; + + if (action_func != null) { + action_func(); + event.stopPropagation(); + return false; + } + } + }, + switchPanelMode: function(wide) { + if (App.isCombinedMode()) return; - return true; - }, - updateTitle: function() { - let tmp = "Tiny Tiny RSS"; + const article_id = Article.getActive(); - if (this.global_unread > 0) { - tmp = "(" + this.global_unread + ") " + tmp; - } + if (wide) { + dijit.byId("headlines-wrap-inner").attr("design", 'sidebar'); + dijit.byId("content-insert").attr("region", "trailing"); - document.title = tmp; - }, - onViewModeChanged: function() { - ArticleCache.clear(); - return Feeds.reloadCurrent(''); - }, - isCombinedMode: function() { - return getInitParam("combined_display_mode"); - }, - hotkeyHandler(event) { - if (event.target.nodeName == "INPUT" || event.target.nodeName == "TEXTAREA") return; - - const action_name = Utils.keyeventToAction(event); - - if (action_name) { - const action_func = this.hotkey_actions[action_name]; - - if (action_func != null) { - action_func(); - event.stopPropagation(); - return false; - } - } - }, - switchPanelMode: function(wide) { - if (App.isCombinedMode()) return; + dijit.byId("content-insert").domNode.setStyle({width: '50%', + height: 'auto', + borderTopWidth: '0px' }); - const article_id = Article.getActive(); + if (parseInt(Cookie.get("ttrss_ci_width")) > 0) { + dijit.byId("content-insert").domNode.setStyle( + {width: Cookie.get("ttrss_ci_width") + "px" }); + } - if (wide) { - dijit.byId("headlines-wrap-inner").attr("design", 'sidebar'); - dijit.byId("content-insert").attr("region", "trailing"); + $("headlines-frame").setStyle({ borderBottomWidth: '0px' }); + $("headlines-frame").addClassName("wide"); - dijit.byId("content-insert").domNode.setStyle({width: '50%', - height: 'auto', - borderTopWidth: '0px' }); + } else { - if (parseInt(Cookie.get("ttrss_ci_width")) > 0) { - dijit.byId("content-insert").domNode.setStyle( - {width: Cookie.get("ttrss_ci_width") + "px" }); - } + dijit.byId("content-insert").attr("region", "bottom"); - $("headlines-frame").setStyle({ borderBottomWidth: '0px' }); - $("headlines-frame").addClassName("wide"); + dijit.byId("content-insert").domNode.setStyle({width: 'auto', + height: '50%', + borderTopWidth: '0px'}); - } else { + if (parseInt(Cookie.get("ttrss_ci_height")) > 0) { + dijit.byId("content-insert").domNode.setStyle( + {height: Cookie.get("ttrss_ci_height") + "px" }); + } - dijit.byId("content-insert").attr("region", "bottom"); + $("headlines-frame").setStyle({ borderBottomWidth: '1px' }); + $("headlines-frame").removeClassName("wide"); - dijit.byId("content-insert").domNode.setStyle({width: 'auto', - height: '50%', - borderTopWidth: '0px'}); + } - if (parseInt(Cookie.get("ttrss_ci_height")) > 0) { - dijit.byId("content-insert").domNode.setStyle( - {height: Cookie.get("ttrss_ci_height") + "px" }); - } + Article.close(); - $("headlines-frame").setStyle({ borderBottomWidth: '1px' }); - $("headlines-frame").removeClassName("wide"); + if (article_id) Article.view(article_id); - } + xhrPost("backend.php", {op: "rpc", method: "setpanelmode", wide: wide ? 1 : 0}); + }, + initHotkeyActions: function() { + this.hotkey_actions["next_feed"] = function () { + const rv = dijit.byId("feedTree").getNextFeed( + Feeds.getActive(), Feeds.activeIsCat()); - Article.close(); - - if (article_id) Article.view(article_id); - - xhrPost("backend.php", {op: "rpc", method: "setpanelmode", wide: wide ? 1 : 0}); - }, - initHotkeyActions: function() { - this.hotkey_actions["next_feed"] = function () { - const rv = dijit.byId("feedTree").getNextFeed( - Feeds.getActive(), Feeds.activeIsCat()); - - if (rv) Feeds.open({feed: rv[0], is_cat: rv[1], delayed: true}) - }; - this.hotkey_actions["prev_feed"] = function () { - const rv = dijit.byId("feedTree").getPreviousFeed( - Feeds.getActive(), Feeds.activeIsCat()); - - if (rv) Feeds.open({feed: rv[0], is_cat: rv[1], delayed: true}) - }; - this.hotkey_actions["next_article"] = function () { - Headlines.move('next'); - }; - this.hotkey_actions["prev_article"] = function () { - Headlines.move('prev'); - }; - this.hotkey_actions["next_article_noscroll"] = function () { - Headlines.move('next', true); - }; - this.hotkey_actions["prev_article_noscroll"] = function () { - Headlines.move('prev', true); - }; - this.hotkey_actions["next_article_noexpand"] = function () { - Headlines.move('next', true, true); - }; - this.hotkey_actions["prev_article_noexpand"] = function () { - Headlines.move('prev', true, true); - }; - this.hotkey_actions["search_dialog"] = function () { - Feeds.search(); - }; - this.hotkey_actions["toggle_mark"] = function () { - Headlines.selectionToggleMarked(); - }; - this.hotkey_actions["toggle_publ"] = function () { - Headlines.selectionTogglePublished(); - }; - this.hotkey_actions["toggle_unread"] = function () { - Headlines.selectionToggleUnread({no_error: 1}); - }; - this.hotkey_actions["edit_tags"] = function () { - const id = Article.getActive(); - if (id) { - Article.editTags(id); - } - }; - this.hotkey_actions["open_in_new_window"] = function () { - if (Article.getActive()) { - Article.openInNewWindow(Article.getActive()); - } - }; - this.hotkey_actions["catchup_below"] = function () { - Headlines.catchupRelativeTo(1); - }; - this.hotkey_actions["catchup_above"] = function () { - Headlines.catchupRelativeTo(0); - }; - this.hotkey_actions["article_scroll_down"] = function () { - Article.scroll(40); - }; - this.hotkey_actions["article_scroll_up"] = function () { - Article.scroll(-40); - }; - this.hotkey_actions["close_article"] = function () { - if (App.isCombinedMode()) { - Article.cdmUnsetActive(); - } else { - Article.close(); - } - }; - this.hotkey_actions["email_article"] = function () { - if (typeof emailArticle != "undefined") { - emailArticle(); - } else if (typeof mailtoArticle != "undefined") { - mailtoArticle(); - } else { - alert(__("Please enable mail plugin first.")); - } - }; - this.hotkey_actions["select_all"] = function () { - Headlines.select('all'); - }; - this.hotkey_actions["select_unread"] = function () { - Headlines.select('unread'); - }; - this.hotkey_actions["select_marked"] = function () { - Headlines.select('marked'); - }; - this.hotkey_actions["select_published"] = function () { - Headlines.select('published'); - }; - this.hotkey_actions["select_invert"] = function () { - Headlines.select('invert'); - }; - this.hotkey_actions["select_none"] = function () { - Headlines.select('none'); - }; - this.hotkey_actions["feed_refresh"] = function () { - if (Feeds.getActive() != undefined) { - Feeds.open({feed: Feeds.getActive(), is_cat: Feeds.activeIsCat()}); - } - }; - this.hotkey_actions["feed_unhide_read"] = function () { - Feeds.toggleUnread(); - }; - this.hotkey_actions["feed_subscribe"] = function () { - CommonDialogs.quickAddFeed(); - }; - this.hotkey_actions["feed_debug_update"] = function () { - if (!Feeds.activeIsCat() && parseInt(Feeds.getActive()) > 0) { - window.open("backend.php?op=feeds&method=update_debugger&feed_id=" + Feeds.getActive() + - "&csrf_token=" + getInitParam("csrf_token")); - } else { - alert("You can't debug this kind of feed."); - } - }; - - this.hotkey_actions["feed_debug_viewfeed"] = function () { - Feeds.open({feed: Feeds.getActive(), is_cat: Feeds.activeIsCat(), viewfeed_debug: true}); - }; - - this.hotkey_actions["feed_edit"] = function () { - if (Feeds.activeIsCat()) - alert(__("You can't edit this kind of feed.")); - else - CommonDialogs.editFeed(Feeds.getActive()); - }; - this.hotkey_actions["feed_catchup"] = function () { - if (Feeds.getActive() != undefined) { - Feeds.catchupCurrent(); - } - }; - this.hotkey_actions["feed_reverse"] = function () { - Headlines.reverse(); - }; - this.hotkey_actions["feed_toggle_vgroup"] = function () { - xhrPost("backend.php", {op: "rpc", method: "togglepref", key: "VFEED_GROUP_BY_FEED"}, () => { - Feeds.reloadCurrent(); - }) - }; - this.hotkey_actions["catchup_all"] = function () { - Feeds.catchupAll(); - }; - this.hotkey_actions["cat_toggle_collapse"] = function () { - if (Feeds.activeIsCat()) { - dijit.byId("feedTree").collapseCat(Feeds.getActive()); - } - }; - this.hotkey_actions["goto_all"] = function () { - Feeds.open({feed: -4}); - }; - this.hotkey_actions["goto_fresh"] = function () { - Feeds.open({feed: -3}); - }; - this.hotkey_actions["goto_marked"] = function () { - Feeds.open({feed: -1}); - }; - this.hotkey_actions["goto_published"] = function () { - Feeds.open({feed: -2}); - }; - this.hotkey_actions["goto_tagcloud"] = function () { - Utils.displayDlg(__("Tag cloud"), "printTagCloud"); - }; - this.hotkey_actions["goto_prefs"] = function () { - document.location.href = "prefs.php"; - }; - this.hotkey_actions["select_article_cursor"] = function () { - const id = Article.getUnderPointer(); - if (id) { - const row = $("RROW-" + id); - - if (row) { - const cb = dijit.getEnclosingWidget( - row.select(".rchk")[0]); - - if (cb) { - if (!row.hasClassName("active")) - cb.attr("checked", !cb.attr("checked")); - - Headlines.onRowChecked(cb); - return false; - } - } - } - }; - this.hotkey_actions["create_label"] = function () { - CommonDialogs.addLabel(); - }; - this.hotkey_actions["create_filter"] = function () { - Filters.quickAddFilter(); - }; - this.hotkey_actions["collapse_sidebar"] = function () { - Feeds.reloadCurrent(); - }; - this.hotkey_actions["toggle_embed_original"] = function () { - if (typeof embedOriginalArticle != "undefined") { - if (Article.getActive()) - embedOriginalArticle(Article.getActive()); - } else { - alert(__("Please enable embed_original plugin first.")); - } - }; - this.hotkey_actions["toggle_widescreen"] = function () { - if (!App.isCombinedMode()) { - App._widescreen_mode = !App._widescreen_mode; - - // reset stored sizes because geometry changed - Cookie.set("ttrss_ci_width", 0); - Cookie.set("ttrss_ci_height", 0); - - App.switchPanelMode(App._widescreen_mode); - } else { - alert(__("Widescreen is not available in combined mode.")); - } - }; - this.hotkey_actions["help_dialog"] = function () { - Utils.helpDialog("main"); - }; - this.hotkey_actions["toggle_combined_mode"] = function () { - Notify.progress("Loading, please wait..."); - - const value = App.isCombinedMode() ? "false" : "true"; - - xhrPost("backend.php", {op: "rpc", method: "setpref", key: "COMBINED_DISPLAY_MODE", value: value}, () => { - setInitParam("combined_display_mode", - !getInitParam("combined_display_mode")); - - Article.close(); - Feeds.reloadCurrent(); - }) - }; - this.hotkey_actions["toggle_cdm_expanded"] = function () { - Notify.progress("Loading, please wait..."); - - const value = getInitParam("cdm_expanded") ? "false" : "true"; - - xhrPost("backend.php", {op: "rpc", method: "setpref", key: "CDM_EXPANDED", value: value}, () => { - setInitParam("cdm_expanded", !getInitParam("cdm_expanded")); - Feeds.reloadCurrent(); - }); - }; - }, - onActionSelected: function(opid) { - switch (opid) { - case "qmcPrefs": - document.location.href = "prefs.php"; - break; - case "qmcLogout": - document.location.href = "backend.php?op=logout"; - break; - case "qmcTagCloud": - Utils.displayDlg(__("Tag cloud"), "printTagCloud"); - break; - case "qmcSearch": - Feeds.search(); - break; - case "qmcAddFeed": - CommonDialogs.quickAddFeed(); - break; - case "qmcDigest": - window.location.href = "backend.php?op=digest"; - break; - case "qmcEditFeed": - if (Feeds.activeIsCat()) - alert(__("You can't edit this kind of feed.")); - else - CommonDialogs.editFeed(Feeds.getActive()); - break; - case "qmcRemoveFeed": - const actid = Feeds.getActive(); - - if (!actid) { - alert(__("Please select some feed first.")); - return; - } + if (rv) Feeds.open({feed: rv[0], is_cat: rv[1], delayed: true}) + }; + this.hotkey_actions["prev_feed"] = function () { + const rv = dijit.byId("feedTree").getPreviousFeed( + Feeds.getActive(), Feeds.activeIsCat()); - if (Feeds.activeIsCat()) { - alert(__("You can't unsubscribe from the category.")); - return; - } + if (rv) Feeds.open({feed: rv[0], is_cat: rv[1], delayed: true}) + }; + this.hotkey_actions["next_article"] = function () { + Headlines.move('next'); + }; + this.hotkey_actions["prev_article"] = function () { + Headlines.move('prev'); + }; + this.hotkey_actions["next_article_noscroll"] = function () { + Headlines.move('next', true); + }; + this.hotkey_actions["prev_article_noscroll"] = function () { + Headlines.move('prev', true); + }; + this.hotkey_actions["next_article_noexpand"] = function () { + Headlines.move('next', true, true); + }; + this.hotkey_actions["prev_article_noexpand"] = function () { + Headlines.move('prev', true, true); + }; + this.hotkey_actions["search_dialog"] = function () { + Feeds.search(); + }; + this.hotkey_actions["toggle_mark"] = function () { + Headlines.selectionToggleMarked(); + }; + this.hotkey_actions["toggle_publ"] = function () { + Headlines.selectionTogglePublished(); + }; + this.hotkey_actions["toggle_unread"] = function () { + Headlines.selectionToggleUnread({no_error: 1}); + }; + this.hotkey_actions["edit_tags"] = function () { + const id = Article.getActive(); + if (id) { + Article.editTags(id); + } + }; + this.hotkey_actions["open_in_new_window"] = function () { + if (Article.getActive()) { + Article.openInNewWindow(Article.getActive()); + } + }; + this.hotkey_actions["catchup_below"] = function () { + Headlines.catchupRelativeTo(1); + }; + this.hotkey_actions["catchup_above"] = function () { + Headlines.catchupRelativeTo(0); + }; + this.hotkey_actions["article_scroll_down"] = function () { + Article.scroll(40); + }; + this.hotkey_actions["article_scroll_up"] = function () { + Article.scroll(-40); + }; + this.hotkey_actions["close_article"] = function () { + if (App.isCombinedMode()) { + Article.cdmUnsetActive(); + } else { + Article.close(); + } + }; + this.hotkey_actions["email_article"] = function () { + if (typeof emailArticle != "undefined") { + emailArticle(); + } else if (typeof mailtoArticle != "undefined") { + mailtoArticle(); + } else { + alert(__("Please enable mail plugin first.")); + } + }; + this.hotkey_actions["select_all"] = function () { + Headlines.select('all'); + }; + this.hotkey_actions["select_unread"] = function () { + Headlines.select('unread'); + }; + this.hotkey_actions["select_marked"] = function () { + Headlines.select('marked'); + }; + this.hotkey_actions["select_published"] = function () { + Headlines.select('published'); + }; + this.hotkey_actions["select_invert"] = function () { + Headlines.select('invert'); + }; + this.hotkey_actions["select_none"] = function () { + Headlines.select('none'); + }; + this.hotkey_actions["feed_refresh"] = function () { + if (Feeds.getActive() != undefined) { + Feeds.open({feed: Feeds.getActive(), is_cat: Feeds.activeIsCat()}); + } + }; + this.hotkey_actions["feed_unhide_read"] = function () { + Feeds.toggleUnread(); + }; + this.hotkey_actions["feed_subscribe"] = function () { + CommonDialogs.quickAddFeed(); + }; + this.hotkey_actions["feed_debug_update"] = function () { + if (!Feeds.activeIsCat() && parseInt(Feeds.getActive()) > 0) { + window.open("backend.php?op=feeds&method=update_debugger&feed_id=" + Feeds.getActive() + + "&csrf_token=" + App.getInitParam("csrf_token")); + } else { + alert("You can't debug this kind of feed."); + } + }; - const fn = Feeds.getName(actid); + this.hotkey_actions["feed_debug_viewfeed"] = function () { + Feeds.open({feed: Feeds.getActive(), is_cat: Feeds.activeIsCat(), viewfeed_debug: true}); + }; - if (confirm(__("Unsubscribe from %s?").replace("%s", fn))) { - CommonDialogs.unsubscribeFeed(actid); - } - break; - case "qmcCatchupAll": - Feeds.catchupAll(); - break; - case "qmcShowOnlyUnread": - Feeds.toggleUnread(); - break; - case "qmcToggleWidescreen": - if (!App.isCombinedMode()) { - App._widescreen_mode = !App._widescreen_mode; - - // reset stored sizes because geometry changed - Cookie.set("ttrss_ci_width", 0); - Cookie.set("ttrss_ci_height", 0); - - App.switchPanelMode(App._widescreen_mode); - } else { - alert(__("Widescreen is not available in combined mode.")); + this.hotkey_actions["feed_edit"] = function () { + if (Feeds.activeIsCat()) + alert(__("You can't edit this kind of feed.")); + else + CommonDialogs.editFeed(Feeds.getActive()); + }; + this.hotkey_actions["feed_catchup"] = function () { + if (Feeds.getActive() != undefined) { + Feeds.catchupCurrent(); + } + }; + this.hotkey_actions["feed_reverse"] = function () { + Headlines.reverse(); + }; + this.hotkey_actions["feed_toggle_vgroup"] = function () { + xhrPost("backend.php", {op: "rpc", method: "togglepref", key: "VFEED_GROUP_BY_FEED"}, () => { + Feeds.reloadCurrent(); + }) + }; + this.hotkey_actions["catchup_all"] = function () { + Feeds.catchupAll(); + }; + this.hotkey_actions["cat_toggle_collapse"] = function () { + if (Feeds.activeIsCat()) { + dijit.byId("feedTree").collapseCat(Feeds.getActive()); + } + }; + this.hotkey_actions["goto_all"] = function () { + Feeds.open({feed: -4}); + }; + this.hotkey_actions["goto_fresh"] = function () { + Feeds.open({feed: -3}); + }; + this.hotkey_actions["goto_marked"] = function () { + Feeds.open({feed: -1}); + }; + this.hotkey_actions["goto_published"] = function () { + Feeds.open({feed: -2}); + }; + this.hotkey_actions["goto_tagcloud"] = function () { + Utils.displayDlg(__("Tag cloud"), "printTagCloud"); + }; + this.hotkey_actions["goto_prefs"] = function () { + document.location.href = "prefs.php"; + }; + this.hotkey_actions["select_article_cursor"] = function () { + const id = Article.getUnderPointer(); + if (id) { + const row = $("RROW-" + id); + + if (row) { + const cb = dijit.getEnclosingWidget( + row.select(".rchk")[0]); + + if (cb) { + if (!row.hasClassName("active")) + cb.attr("checked", !cb.attr("checked")); + + Headlines.onRowChecked(cb); + return false; + } + } + } + }; + this.hotkey_actions["create_label"] = function () { + CommonDialogs.addLabel(); + }; + this.hotkey_actions["create_filter"] = function () { + Filters.quickAddFilter(); + }; + this.hotkey_actions["collapse_sidebar"] = function () { + Feeds.reloadCurrent(); + }; + this.hotkey_actions["toggle_embed_original"] = function () { + if (typeof embedOriginalArticle != "undefined") { + if (Article.getActive()) + embedOriginalArticle(Article.getActive()); + } else { + alert(__("Please enable embed_original plugin first.")); + } + }; + this.hotkey_actions["toggle_widescreen"] = function () { + if (!App.isCombinedMode()) { + App._widescreen_mode = !App._widescreen_mode; + + // reset stored sizes because geometry changed + Cookie.set("ttrss_ci_width", 0); + Cookie.set("ttrss_ci_height", 0); + + App.switchPanelMode(App._widescreen_mode); + } else { + alert(__("Widescreen is not available in combined mode.")); + } + }; + this.hotkey_actions["help_dialog"] = function () { + Utils.helpDialog("main"); + }; + this.hotkey_actions["toggle_combined_mode"] = function () { + Notify.progress("Loading, please wait..."); + + const value = App.isCombinedMode() ? "false" : "true"; + + xhrPost("backend.php", {op: "rpc", method: "setpref", key: "COMBINED_DISPLAY_MODE", value: value}, () => { + App.setInitParam("combined_display_mode", + !App.getInitParam("combined_display_mode")); + + Article.close(); + Feeds.reloadCurrent(); + }) + }; + this.hotkey_actions["toggle_cdm_expanded"] = function () { + Notify.progress("Loading, please wait..."); + + const value = App.getInitParam("cdm_expanded") ? "false" : "true"; + + xhrPost("backend.php", {op: "rpc", method: "setpref", key: "CDM_EXPANDED", value: value}, () => { + App.setInitParam("cdm_expanded", !App.getInitParam("cdm_expanded")); + Feeds.reloadCurrent(); + }); + }; + }, + onActionSelected: function(opid) { + switch (opid) { + case "qmcPrefs": + document.location.href = "prefs.php"; + break; + case "qmcLogout": + document.location.href = "backend.php?op=logout"; + break; + case "qmcTagCloud": + Utils.displayDlg(__("Tag cloud"), "printTagCloud"); + break; + case "qmcSearch": + Feeds.search(); + break; + case "qmcAddFeed": + CommonDialogs.quickAddFeed(); + break; + case "qmcDigest": + window.location.href = "backend.php?op=digest"; + break; + case "qmcEditFeed": + if (Feeds.activeIsCat()) + alert(__("You can't edit this kind of feed.")); + else + CommonDialogs.editFeed(Feeds.getActive()); + break; + case "qmcRemoveFeed": + const actid = Feeds.getActive(); + + if (!actid) { + alert(__("Please select some feed first.")); + return; + } + + if (Feeds.activeIsCat()) { + alert(__("You can't unsubscribe from the category.")); + return; + } + + const fn = Feeds.getName(actid); + + if (confirm(__("Unsubscribe from %s?").replace("%s", fn))) { + CommonDialogs.unsubscribeFeed(actid); + } + break; + case "qmcCatchupAll": + Feeds.catchupAll(); + break; + case "qmcShowOnlyUnread": + Feeds.toggleUnread(); + break; + case "qmcToggleWidescreen": + if (!App.isCombinedMode()) { + App._widescreen_mode = !App._widescreen_mode; + + // reset stored sizes because geometry changed + Cookie.set("ttrss_ci_width", 0); + Cookie.set("ttrss_ci_height", 0); + + App.switchPanelMode(App._widescreen_mode); + } else { + alert(__("Widescreen is not available in combined mode.")); + } + break; + case "qmcHKhelp": + Utils.helpDialog("main"); + break; + default: + console.log("quickMenuGo: unknown action: " + opid); + } + }, + isPrefs: function() { + return false; } - break; - case "qmcHKhelp": - Utils.helpDialog("main"); - break; - default: - console.log("quickMenuGo: unknown action: " + opid); + }); + + App = new _App(); + } catch (e) { + exception_error(e); } - }, - isPrefs: function() { - return false; - } -}; + }); +}); function hash_get(key) { const kv = window.location.hash.substring(1).toQueryParams(); diff --git a/prefs.php b/prefs.php index 93773103f..a3d7c8b1b 100644 --- a/prefs.php +++ b/prefs.php @@ -100,13 +100,6 @@ - - - -- cgit v1.2.3-54-g00ecf From 5ead558e435dd8d58f6666b445374b0005a60337 Mon Sep 17 00:00:00 2001 From: Andrew Dolgov Date: Sun, 2 Dec 2018 22:08:18 +0300 Subject: move Utils to AppBase where it belongs --- classes/feeds.php | 4 +- classes/pref/feeds.php | 4 +- js/AppBase.js | 325 +++++++++++++++++++++++++++++++++++++++++++++++- js/Article.js | 4 +- js/Feeds.js | 14 +-- js/Headlines.js | 26 ++-- js/Utils.js | 330 ------------------------------------------------- js/prefs.js | 25 ++-- js/tt-rss.js | 19 ++- 9 files changed, 370 insertions(+), 381 deletions(-) delete mode 100644 js/Utils.js (limited to 'js/tt-rss.js') diff --git a/classes/feeds.php b/classes/feeds.php index 1e62a9206..3c6c20f26 100755 --- a/classes/feeds.php +++ b/classes/feeds.php @@ -51,7 +51,7 @@ class Feeds extends Handler_Protected { $reply .= " + onclick=\"App.displayDlg('".__("Show as feed")."','generatedFeed', '$feed_id:$is_cat:$rss_link')\"> "; @@ -137,7 +137,7 @@ class Feeds extends Handler_Protected { //$reply .= ""; - $reply .= ""; $reply .= ""; diff --git a/classes/pref/feeds.php b/classes/pref/feeds.php index 82cb84daf..961a09c28 100755 --- a/classes/pref/feeds.php +++ b/classes/pref/feeds.php @@ -1306,7 +1306,7 @@ class Pref_Feeds extends Handler_Protected { print_warning("Published OPML does not include your Tiny Tiny RSS settings, feeds that require authentication or feeds hidden from Popular feeds."); - print " "; PluginHost::getInstance()->run_hooks(PluginHost::HOOK_PREFS_TAB_SECTION, @@ -1323,7 +1323,7 @@ class Pref_Feeds extends Handler_Protected { print "

    "; - print " "; print "

    - +
    0) { ?> diff --git a/js/AppBase.js b/js/AppBase.js index ce040e8c9..9ab2f507e 100644 --- a/js/AppBase.js +++ b/js/AppBase.js @@ -7,15 +7,15 @@ define(["dojo/_base/declare"], function (declare) { hotkey_prefix: 0, hotkey_prefix_pressed: false, hotkey_prefix_timeout: 0, + constructor: function() { + window.onerror = this.Error.onWindowError; + }, getInitParam: function(k) { return this._initParams[k]; }, setInitParam: function(k, v) { this._initParams[k] = v; }, - constructor: function(args) { - // - }, enableCsrfSupport: function() { Ajax.Base.prototype.initialize = Ajax.Base.prototype.initialize.wrap( function (callOriginal, options) { @@ -176,7 +176,7 @@ define(["dojo/_base/declare"], function (declare) { if (callback) callback(transport); } catch (e) { - exception_error(e); + this.Error.report(e); } }); @@ -355,5 +355,67 @@ define(["dojo/_base/declare"], function (declare) { explainError: function(code) { return this.displayDlg(__("Error explained"), "explainError", code); }, + Error: { + report: function(error, params) { + params = params || {}; + + if (!error) return; + + console.error("[Error.report]", error, params); + + const message = params.message ? params.message : error.toString(); + + try { + xhrPost("backend.php", + {op: "rpc", method: "log", + file: params.filename ? params.filename : error.fileName, + line: params.lineno ? params.lineno : error.lineNumber, + msg: message, + context: error.stack}, + (transport) => { + console.warn("[Error.report] log response", transport.responseText); + }); + } catch (re) { + console.error("[Error.report] exception while saving logging error on server", re); + } + + try { + if (dijit.byId("exceptionDlg")) + dijit.byId("exceptionDlg").destroyRecursive(); + + let content = "

    " + message + "

    "; + + if (error.stack) + content += "
    Stack trace:
    " + + ""; + + content += "
    "; + + content += ""; + content += "
    "; + + const dialog = new dijit.Dialog({ + id: "exceptionDlg", + title: "Unhandled exception", + style: "width: 600px", + content: content + }); + + dialog.show(); + } catch (de) { + console.error("[Error.report] exception while showing error dialog", de); + + alert(error.stack ? error.stack : message); + } + + }, + onWindowError: function (message, filename, lineno, colno, error) { + // called without context (this) from window.onerror + App.Error.report(error, + {message: message, filename: filename, lineno: lineno, colno: colno}); + }, + } }); }); diff --git a/js/Article.js b/js/Article.js index d3ae8eed7..04cba8ab7 100644 --- a/js/Article.js +++ b/js/Article.js @@ -168,7 +168,7 @@ define(["dojo/_base/declare"], function (declare) { Notify.close(); } catch (e) { - exception_error(e); + App.Error.report(e); } }) } @@ -206,7 +206,7 @@ define(["dojo/_base/declare"], function (declare) { if (tooltip) tooltip.attr('label', data.content_full); } } catch (e) { - exception_error(e); + App.Error.report(e); } }); } diff --git a/js/CommonDialogs.js b/js/CommonDialogs.js index b9cee8873..81ad2ffce 100644 --- a/js/CommonDialogs.js +++ b/js/CommonDialogs.js @@ -152,7 +152,7 @@ define(["dojo/_base/declare"], function (declare) { } catch (e) { console.error(transport.responseText); - exception_error(e); + App.Error.report(e); } }); } diff --git a/js/CommonFilters.js b/js/CommonFilters.js index d2a3e6317..97a676c98 100644 --- a/js/CommonFilters.js +++ b/js/CommonFilters.js @@ -67,7 +67,7 @@ define(["dojo/_base/declare"], function (declare) { parentNode.appendChild(li); } } catch (e) { - exception_error(e); + App.Error.report(e); } }); }, @@ -117,7 +117,7 @@ define(["dojo/_base/declare"], function (declare) { } } catch (e) { - exception_error(e); + App.Error.report(e); } }); }, @@ -238,7 +238,7 @@ define(["dojo/_base/declare"], function (declare) { console.log("getTestResults: dialog closed, bailing out."); } } catch (e) { - exception_error(e); + App.Error.report(e); } }); diff --git a/js/FeedTree.js b/js/FeedTree.js index 37e3de2d1..75d1c901b 100755 --- a/js/FeedTree.js +++ b/js/FeedTree.js @@ -207,7 +207,7 @@ define(["dojo/_base/declare", "dojo/dom-construct", "dijit/Tree", "dijit/Menu"], } } } catch (e) { - exception_error(e); + App.Error.report(e); } }, findNodeParentsAndExpandThem: function(feed, is_cat, root, parents) { @@ -242,7 +242,7 @@ define(["dojo/_base/declare", "dojo/dom-construct", "dijit/Tree", "dijit/Menu"], this.expandParentNodes(feed, is_cat, parents.slice(0)); } } catch (e) { - exception_error(e); + App.Error.report(e); } }, selectFeed: function(feed, is_cat) { diff --git a/js/Feeds.js b/js/Feeds.js index eb9a468ad..fbcb56150 100644 --- a/js/Feeds.js +++ b/js/Feeds.js @@ -198,13 +198,13 @@ define(["dojo/_base/declare"], function (declare) { Feeds.init(); App.setLoadingProgress(25); } catch (e) { - exception_error(e); + App.Error.report(e); } }); tree.startup(); } catch (e) { - exception_error(e); + App.Error.report(e); } }, init: function() { @@ -380,7 +380,7 @@ define(["dojo/_base/declare"], function (declare) { Headlines.onLoaded(transport, offset); PluginHost.run(PluginHost.HOOK_FEED_LOADED, [feed, is_cat]); } catch (e) { - exception_error(e); + App.Error.report(e); } }); }); diff --git a/js/common.js b/js/common.js index de6d13a78..427e3034c 100755 --- a/js/common.js +++ b/js/common.js @@ -4,6 +4,16 @@ let _label_base_index = -1024; let loading_progress = 0; +/* error reporting shim */ + +// TODO: deprecated; remove +function exception_error(e, e_compat, filename, lineno, colno) { + if (typeof e == "string") + e = e_compat; + + App.Error.report(e, {filename: filename, lineno: lineno, colno: colno}); +} + /* xhr shorthand helpers */ function xhrPost(url, params, complete) { @@ -118,71 +128,6 @@ const Cookie = { } }; -/* error reporting */ - -function report_error(message, filename, lineno, colno, error) { - exception_error(error, null, filename, lineno); -} - -function exception_error(e, e_compat, filename, lineno, colno) { - if (typeof e == "string") e = e_compat; - - if (!e) return; // no exception object, nothing to report. - - try { - console.error(e); - const msg = e.toString(); - - try { - xhrPost("backend.php", - {op: "rpc", method: "log", - file: e.fileName ? e.fileName : filename, - line: e.lineNumber ? e.lineNumber : lineno, - msg: msg, context: e.stack}, - (transport) => { - console.warn(transport.responseText); - }); - - } catch (e) { - console.error("Exception while trying to log the error.", e); - } - - let content = "

    " + msg + "

    "; - - if (e.stack) { - content += "
    Stack trace:
    " + - ""; - } - - content += "
    "; - - content += "
    "; - - content += ""; - content += "
    "; - - if (dijit.byId("exceptionDlg")) - dijit.byId("exceptionDlg").destroyRecursive(); - - const dialog = new dijit.Dialog({ - id: "exceptionDlg", - title: "Unhandled exception", - style: "width: 600px", - content: content}); - - dialog.show(); - - } catch (ei) { - console.error("Exception while trying to report an exception:", ei); - console.error("Original exception:", e); - - alert("Exception occured while trying to report an exception.\n" + - ei.stack + "\n\nOriginal exception:\n" + e.stack); - } -} - /* runtime notifications */ const Notify = { diff --git a/js/prefs.js b/js/prefs.js index dafdbcdee..c89c0494f 100755 --- a/js/prefs.js +++ b/js/prefs.js @@ -58,10 +58,6 @@ require(["dojo/_base/kernel", try { const _App = declare("fox.App", AppBase, { constructor: function() { - window.onerror = function (message, filename, lineno, colno, error) { - report_error(message, filename, lineno, colno, error); - }; - parser.parse(); this.setLoadingProgress(50); @@ -73,7 +69,7 @@ require(["dojo/_base/kernel", try { this.backendSanityCallback(transport); } catch (e) { - exception_error(e); + this.Error.report(e); } }); }, @@ -149,7 +145,7 @@ require(["dojo/_base/kernel", App = new _App(); } catch (e) { - exception_error(e); + this.Error.report(e); } }); }); \ No newline at end of file diff --git a/js/tt-rss.js b/js/tt-rss.js index 97d34fbc1..8931e9860 100644 --- a/js/tt-rss.js +++ b/js/tt-rss.js @@ -65,10 +65,6 @@ require(["dojo/_base/kernel", _widescreen_mode: false, hotkey_actions: {}, constructor: function () { - window.onerror = function (message, filename, lineno, colno, error) { - report_error(message, filename, lineno, colno, error); - }; - parser.parse(); this.setLoadingProgress(30); @@ -91,7 +87,7 @@ require(["dojo/_base/kernel", try { App.backendSanityCallback(transport); } catch (e) { - exception_error(e); + App.Error.report(e); } }); }, @@ -555,7 +551,7 @@ require(["dojo/_base/kernel", App = new _App(); } catch (e) { - exception_error(e); + App.Error.report(e); } }); }); diff --git a/plugins/embed_original/init.js b/plugins/embed_original/init.js index 6f797556b..1e9fcb253 100644 --- a/plugins/embed_original/init.js +++ b/plugins/embed_original/init.js @@ -1,60 +1,56 @@ function embedOriginalArticle(id) { - try { - const hasSandbox = "sandbox" in document.createElement("iframe"); + const hasSandbox = "sandbox" in document.createElement("iframe"); - if (!hasSandbox) { - alert(__("Sorry, your browser does not support sandboxed iframes.")); - return; - } + if (!hasSandbox) { + alert(__("Sorry, your browser does not support sandboxed iframes.")); + return; + } - let c = false; + let c = false; + + if (App.isCombinedMode()) { + c = $$("div#RROW-" + id + " div[class=content-inner]")[0]; + } else if (id == Article.getActive()) { + c = $$(".post .content")[0]; + } + + if (c) { + const iframe = c.parentNode.getElementsByClassName("embeddedContent")[0]; + + if (iframe) { + Element.show(c); + c.parentNode.removeChild(iframe); + + if (App.isCombinedMode()) { + Article.cdmScrollToId(id, true); + } - if (App.isCombinedMode()) { - c = $$("div#RROW-" + id + " div[class=content-inner]")[0]; - } else if (id == Article.getActive()) { - c = $$(".post .content")[0]; + return; } + } - if (c) { - const iframe = c.parentNode.getElementsByClassName("embeddedContent")[0]; + const query = { op: "pluginhandler", plugin: "embed_original", method: "getUrl", id: id }; - if (iframe) { - Element.show(c); - c.parentNode.removeChild(iframe); + xhrJson("backend.php", query, (reply) => { + if (reply) { + const iframe = new Element("iframe", { + class: "embeddedContent", + src: reply.url, + width: (c.parentNode.offsetWidth - 5) + 'px', + height: (c.parentNode.parentNode.offsetHeight - c.parentNode.firstChild.offsetHeight - 5) + 'px', + style: "overflow: auto; border: none; min-height: " + (document.body.clientHeight / 2) + "px;", + sandbox: 'allow-scripts', + }); + + if (c) { + Element.hide(c); + c.parentNode.insertBefore(iframe, c); if (App.isCombinedMode()) { Article.cdmScrollToId(id, true); } - - return; } } + }); - const query = { op: "pluginhandler", plugin: "embed_original", method: "getUrl", id: id }; - - xhrJson("backend.php", query, (reply) => { - if (reply) { - const iframe = new Element("iframe", { - class: "embeddedContent", - src: reply.url, - width: (c.parentNode.offsetWidth - 5) + 'px', - height: (c.parentNode.parentNode.offsetHeight - c.parentNode.firstChild.offsetHeight - 5) + 'px', - style: "overflow: auto; border: none; min-height: " + (document.body.clientHeight / 2) + "px;", - sandbox: 'allow-scripts', - }); - - if (c) { - Element.hide(c); - c.parentNode.insertBefore(iframe, c); - - if (App.isCombinedMode()) { - Article.cdmScrollToId(id, true); - } - } - } - }); - - } catch (e) { - exception_error("embedOriginalArticle", e); - } } diff --git a/plugins/import_export/import_export.js b/plugins/import_export/import_export.js index 56a2a5c3e..8dc5f7570 100644 --- a/plugins/import_export/import_export.js +++ b/plugins/import_export/import_export.js @@ -50,7 +50,7 @@ function exportData() { "Error occured, could not export data."; } } catch (e) { - exception_error("exportData", e, transport.responseText); + App.Error.report(e); } Notify.close(); @@ -71,7 +71,7 @@ function exportData() { } catch (e) { - exception_error("exportData", e); + App.Error.report(e); } } @@ -100,7 +100,7 @@ function dataImportComplete(iframe) { dialog.show(); } catch (e) { - exception_error("dataImportComplete", e); + App.Error.report(e); } } diff --git a/plugins/mail/mail.js b/plugins/mail/mail.js index b72289c2a..87e354b42 100644 --- a/plugins/mail/mail.js +++ b/plugins/mail/mail.js @@ -1,57 +1,52 @@ function emailArticle(id) { - try { - if (!id) { - var ids = Headlines.getSelected(); + if (!id) { + let ids = Headlines.getSelected(); - if (ids.length == 0) { - alert(__("No articles selected.")); - return; - } - - id = ids.toString(); + if (ids.length == 0) { + alert(__("No articles selected.")); + return; } - if (dijit.byId("emailArticleDlg")) - dijit.byId("emailArticleDlg").destroyRecursive(); - - var query = "backend.php?op=pluginhandler&plugin=mail&method=emailArticle¶m=" + encodeURIComponent(id); - - dialog = new dijit.Dialog({ - id: "emailArticleDlg", - title: __("Forward article by email"), - style: "width: 600px", - execute: function() { - if (this.validate()) { - xhrJson("backend.php", this.attr('value'), (reply) => { - if (reply) { - const error = reply['error']; - - if (error) { - alert(__('Error sending email:') + ' ' + error); - } else { - Notify.info('Your message has been sent.'); - dialog.hide(); - } + id = ids.toString(); + } + if (dijit.byId("emailArticleDlg")) + dijit.byId("emailArticleDlg").destroyRecursive(); + + const query = "backend.php?op=pluginhandler&plugin=mail&method=emailArticle¶m=" + encodeURIComponent(id); + + const dialog = new dijit.Dialog({ + id: "emailArticleDlg", + title: __("Forward article by email"), + style: "width: 600px", + execute: function() { + if (this.validate()) { + xhrJson("backend.php", this.attr('value'), (reply) => { + if (reply) { + const error = reply['error']; + + if (error) { + alert(__('Error sending email:') + ' ' + error); + } else { + Notify.info('Your message has been sent.'); + dialog.hide(); } - }); - } - }, - href: query}); - /* var tmph = dojo.connect(dialog, 'onLoad', function() { - dojo.disconnect(tmph); + } + }); + } + }, + href: query}); - new Ajax.Autocompleter('emailArticleDlg_destination', 'emailArticleDlg_dst_choices', - "backend.php?op=pluginhandler&plugin=mail&method=completeEmails", - { tokens: '', paramName: "search" }); - }); */ + /* var tmph = dojo.connect(dialog, 'onLoad', function() { + dojo.disconnect(tmph); - dialog.show(); + new Ajax.Autocompleter('emailArticleDlg_destination', 'emailArticleDlg_dst_choices', + "backend.php?op=pluginhandler&plugin=mail&method=completeEmails", + { tokens: '', paramName: "search" }); + }); */ - } catch (e) { - exception_error("emailArticle", e); - } + dialog.show(); } diff --git a/plugins/mailto/init.js b/plugins/mailto/init.js index dacff725e..92a90f8e9 100644 --- a/plugins/mailto/init.js +++ b/plugins/mailto/init.js @@ -1,32 +1,27 @@ function mailtoArticle(id) { - try { - if (!id) { - const ids = Headlines.getSelected(); + if (!id) { + const ids = Headlines.getSelected(); - if (ids.length == 0) { - alert(__("No articles selected.")); - return; - } - - id = ids.toString(); + if (ids.length == 0) { + alert(__("No articles selected.")); + return; } - if (dijit.byId("emailArticleDlg")) - dijit.byId("emailArticleDlg").destroyRecursive(); + id = ids.toString(); + } - const query = "backend.php?op=pluginhandler&plugin=mailto&method=emailArticle¶m=" + encodeURIComponent(id); + if (dijit.byId("emailArticleDlg")) + dijit.byId("emailArticleDlg").destroyRecursive(); - dialog = new dijit.Dialog({ - id: "emailArticleDlg", - title: __("Forward article by email"), - style: "width: 600px", - href: query}); + const query = "backend.php?op=pluginhandler&plugin=mailto&method=emailArticle¶m=" + encodeURIComponent(id); - dialog.show(); + const dialog = new dijit.Dialog({ + id: "emailArticleDlg", + title: __("Forward article by email"), + style: "width: 600px", + href: query}); - } catch (e) { - exception_error("emailArticle", e); - } + dialog.show(); } diff --git a/plugins/nsfw/init.js b/plugins/nsfw/init.js index 40ad2b0ba..adb6d43c0 100644 --- a/plugins/nsfw/init.js +++ b/plugins/nsfw/init.js @@ -1,12 +1,7 @@ function nsfwShow(elem) { - try { - content = elem.parentNode.getElementsBySelector("div.nswf.content")[0]; + let content = elem.parentNode.getElementsBySelector("div.nswf.content")[0]; - if (content) { - Element.toggle(content); - } - - } catch (e) { - exception_error("nswfSHow", e); + if (content) { + Element.toggle(content); } } diff --git a/plugins/shorten_expanded/init.js b/plugins/shorten_expanded/init.js index d9995e8ac..a5424ea38 100644 --- a/plugins/shorten_expanded/init.js +++ b/plugins/shorten_expanded/init.js @@ -1,29 +1,20 @@ var _shorten_expanded_threshold = 1.5; //window heights function expandSizeWrapper(id) { - try { - const row = $(id); + const row = $(id); - console.log(row); + if (row) { + const content = row.select(".contentSizeWrapper")[0]; + const link = row.select(".expandPrompt")[0]; - if (row) { - const content = row.select(".contentSizeWrapper")[0]; - const link = row.select(".expandPrompt")[0]; - - if (content) content.removeClassName("contentSizeWrapper"); - if (link) Element.hide(link); - - } - } catch (e) { - exception_error("expandSizeWrapper", e); + if (content) content.removeClassName("contentSizeWrapper"); + if (link) Element.hide(link); } return false; - } require(['dojo/_base/kernel', 'dojo/ready'], function (dojo, ready) { - ready(function() { PluginHost.register(PluginHost.HOOK_ARTICLE_RENDERED_CDM, function(row) { window.setTimeout(function() { @@ -48,5 +39,4 @@ require(['dojo/_base/kernel', 'dojo/ready'], function (dojo, ready) { return true; }); }); - }); diff --git a/register.php b/register.php index 6c76eed5a..1bd1b2544 100644 --- a/register.php +++ b/register.php @@ -135,13 +135,13 @@ f.sub_btn.disabled = true; } } catch (e) { - exception_error("checkUsername_callback", e); + App.Error.report(e); } } }); } catch (e) { - exception_error("checkUsername", e); + App.Error.report(e); } return false; @@ -171,7 +171,7 @@ return true; } catch (e) { - exception_error("validateRegForm", e); + alert(e.stack); return false; } } -- cgit v1.2.3-54-g00ecf From e76d1fb995e25d78f0131ac56660846b0e9ecb9a Mon Sep 17 00:00:00 2001 From: Andrew Dolgov Date: Mon, 3 Dec 2018 14:21:50 +0300 Subject: plugins: mail, mailto: remove code from global context --- classes/feeds.php | 4 +-- js/tt-rss.js | 8 ++--- plugins/mail/init.php | 2 +- plugins/mail/mail.js | 94 ++++++++++++++++++++++++++----------------------- plugins/mailto/init.js | 45 +++++++++++++---------- plugins/mailto/init.php | 2 +- 6 files changed, 82 insertions(+), 73 deletions(-) (limited to 'js/tt-rss.js') diff --git a/classes/feeds.php b/classes/feeds.php index 58d4f68d9..9fe528723 100755 --- a/classes/feeds.php +++ b/classes/feeds.php @@ -124,12 +124,12 @@ class Feeds extends Handler_Protected { } if (PluginHost::getInstance()->get_plugin("mail")) { - $reply .= ""; } if (PluginHost::getInstance()->get_plugin("mailto")) { - $reply .= ""; } diff --git a/js/tt-rss.js b/js/tt-rss.js index 8931e9860..fc87ae24d 100644 --- a/js/tt-rss.js +++ b/js/tt-rss.js @@ -302,12 +302,10 @@ require(["dojo/_base/kernel", } }; this.hotkey_actions["email_article"] = function () { - if (typeof emailArticle != "undefined") { - emailArticle(); - } else if (typeof mailtoArticle != "undefined") { - mailtoArticle(); + if (typeof Plugins.Mail != "undefined") { + Plugins.Mail.onHotkey(Headlines.getSelected()); } else { - alert(__("Please enable mail plugin first.")); + alert(__("Please enable mail or mailto plugin first.")); } }; this.hotkey_actions["select_all"] = function () { diff --git a/plugins/mail/init.php b/plugins/mail/init.php index d8f92853e..1609a05c3 100644 --- a/plugins/mail/init.php +++ b/plugins/mail/init.php @@ -72,7 +72,7 @@ class Mail extends Plugin { function hook_article_button($line) { return "Zoom"; } diff --git a/plugins/mail/mail.js b/plugins/mail/mail.js index 87e354b42..eb7b7e6b6 100644 --- a/plugins/mail/mail.js +++ b/plugins/mail/mail.js @@ -1,52 +1,56 @@ -function emailArticle(id) { - if (!id) { - let ids = Headlines.getSelected(); +Plugins.Mail = { + send: function(id) { + if (!id) { + let ids = Headlines.getSelected(); + + if (ids.length == 0) { + alert(__("No articles selected.")); + return; + } - if (ids.length == 0) { - alert(__("No articles selected.")); - return; + id = ids.toString(); } - id = ids.toString(); - } + if (dijit.byId("emailArticleDlg")) + dijit.byId("emailArticleDlg").destroyRecursive(); - if (dijit.byId("emailArticleDlg")) - dijit.byId("emailArticleDlg").destroyRecursive(); - - const query = "backend.php?op=pluginhandler&plugin=mail&method=emailArticle¶m=" + encodeURIComponent(id); - - const dialog = new dijit.Dialog({ - id: "emailArticleDlg", - title: __("Forward article by email"), - style: "width: 600px", - execute: function() { - if (this.validate()) { - xhrJson("backend.php", this.attr('value'), (reply) => { - if (reply) { - const error = reply['error']; - - if (error) { - alert(__('Error sending email:') + ' ' + error); - } else { - Notify.info('Your message has been sent.'); - dialog.hide(); - } - - } - }); - } - }, - href: query}); + const query = "backend.php?op=pluginhandler&plugin=mail&method=emailArticle¶m=" + encodeURIComponent(id); - /* var tmph = dojo.connect(dialog, 'onLoad', function() { - dojo.disconnect(tmph); - - new Ajax.Autocompleter('emailArticleDlg_destination', 'emailArticleDlg_dst_choices', - "backend.php?op=pluginhandler&plugin=mail&method=completeEmails", - { tokens: '', paramName: "search" }); - }); */ - - dialog.show(); -} + const dialog = new dijit.Dialog({ + id: "emailArticleDlg", + title: __("Forward article by email"), + style: "width: 600px", + execute: function () { + if (this.validate()) { + xhrJson("backend.php", this.attr('value'), (reply) => { + if (reply) { + const error = reply['error']; + if (error) { + alert(__('Error sending email:') + ' ' + error); + } else { + Notify.info('Your message has been sent.'); + dialog.hide(); + } + } + }); + } + }, + href: query + }); + + /* var tmph = dojo.connect(dialog, 'onLoad', function() { + dojo.disconnect(tmph); + + new Ajax.Autocompleter('emailArticleDlg_destination', 'emailArticleDlg_dst_choices', + "backend.php?op=pluginhandler&plugin=mail&method=completeEmails", + { tokens: '', paramName: "search" }); + }); */ + + dialog.show(); + }, + onHotkey: function(id) { + Plugins.Mail.send(id); + } +}; diff --git a/plugins/mailto/init.js b/plugins/mailto/init.js index 92a90f8e9..f81f70fc7 100644 --- a/plugins/mailto/init.js +++ b/plugins/mailto/init.js @@ -1,27 +1,34 @@ -function mailtoArticle(id) { - if (!id) { - const ids = Headlines.getSelected(); +Plugins.Mailto = { + send: function (id) { + if (!id) { + const ids = Headlines.getSelected(); - if (ids.length == 0) { - alert(__("No articles selected.")); - return; - } + if (ids.length == 0) { + alert(__("No articles selected.")); + return; + } - id = ids.toString(); - } + id = ids.toString(); + } - if (dijit.byId("emailArticleDlg")) - dijit.byId("emailArticleDlg").destroyRecursive(); + if (dijit.byId("emailArticleDlg")) + dijit.byId("emailArticleDlg").destroyRecursive(); - const query = "backend.php?op=pluginhandler&plugin=mailto&method=emailArticle¶m=" + encodeURIComponent(id); + const query = "backend.php?op=pluginhandler&plugin=mailto&method=emailArticle¶m=" + encodeURIComponent(id); - const dialog = new dijit.Dialog({ - id: "emailArticleDlg", - title: __("Forward article by email"), - style: "width: 600px", - href: query}); + const dialog = new dijit.Dialog({ + id: "emailArticleDlg", + title: __("Forward article by email"), + style: "width: 600px", + href: query}); - dialog.show(); -} + dialog.show(); + } +}; +// override default hotkey action if enabled +Plugins.Mail = Plugins.Mail || {}; +Plugins.Mail.onHotkey = function(id) { + Plugins.Mailto.send(id); +}; \ No newline at end of file diff --git a/plugins/mailto/init.php b/plugins/mailto/init.php index 60c58b707..3dbc8d643 100644 --- a/plugins/mailto/init.php +++ b/plugins/mailto/init.php @@ -21,7 +21,7 @@ class MailTo extends Plugin { function hook_article_button($line) { return "Zoom"; } -- cgit v1.2.3-54-g00ecf