From 59843f9e3d222901421a92fff793a1e031f38f65 Mon Sep 17 00:00:00 2001 From: Xia Li-yao Date: Wed, 27 Feb 2019 21:53:27 -0500 Subject: Menu item controlling which instances are expanded/collapsed (#1007) Adds a menu item (like "Quick Jump") for options related to displaying instances. This provides functionality for: * expanding/collapsing all instances on the currently opened page * controlling whether instances are expanded/collapsed by default * controlling whether the state of instances should be "remembered" This new functionality is implemented in Typescript in `details-helper`. The built-in-themes style switcher also got a revamp so that all three of QuickJump, the style switcher, and instance preferences now have the same style and implementation structure. See also: https://mail.haskell.org/pipermail/haskell-cafe/2019-January/130495.html Fixes #698. Co-authored-by: Lysxia Co-authored-by: Nathan Collins --- .../resources/html/Linuwial.std-theme/linuwial.css | 43 +- haddock-api/resources/html/README.md | 8 +- haddock-api/resources/html/haddock-bundle.min.js | 2 +- .../resources/html/js-src/details-helper.ts | 106 ----- .../resources/html/js-src/details-helper.tsx | 464 +++++++++++++++++++++ haddock-api/resources/html/js-src/init.ts | 4 +- haddock-api/resources/html/js-src/style-menu.tsx | 177 ++++---- haddock-api/resources/html/quick-jump.css | 60 ++- 8 files changed, 635 insertions(+), 229 deletions(-) delete mode 100644 haddock-api/resources/html/js-src/details-helper.ts create mode 100644 haddock-api/resources/html/js-src/details-helper.tsx (limited to 'haddock-api/resources/html') diff --git a/haddock-api/resources/html/Linuwial.std-theme/linuwial.css b/haddock-api/resources/html/Linuwial.std-theme/linuwial.css index 7ae19a93..330c605a 100644 --- a/haddock-api/resources/html/Linuwial.std-theme/linuwial.css +++ b/haddock-api/resources/html/Linuwial.std-theme/linuwial.css @@ -468,42 +468,10 @@ table.info { text-align: right; } -div#style-menu-holder { - position: relative; - z-index: 2; - display: inline; -} - -#style-menu { - position: absolute; - z-index: 1; - overflow: visible; - background: #374c5e; - margin: 0; - text-align: center; - right: 0; - padding: 0; - top: 1.25em; -} - #style-menu li { - display: inline-block; + display: block; border-style: none; - margin: 0; - padding: 0; - color: #000; list-style-type: none; - border-top: 1px solid #919191 -} - -#style-menu li + li { - border-left: 1px solid #919191; -} - -#style-menu a { - width: 6em; - padding: 3px; - display: block; } #footer { @@ -896,3 +864,12 @@ div#style-menu-holder { } /* @end */ + +/* @group Dropdown menus */ + +#preferences-menu, #style-menu { + width: 25em; + overflow-y: auto; +} + +/* @end */ diff --git a/haddock-api/resources/html/README.md b/haddock-api/resources/html/README.md index 0552f6fd..d555989d 100644 --- a/haddock-api/resources/html/README.md +++ b/haddock-api/resources/html/README.md @@ -13,4 +13,10 @@ After each change to the TypeScript sources, compile and copy the generated file ``` gulp && cp *.min.js path-to/generated-haddock-docs && cp *.js.map path-to/generated-haddock-docs -``` \ No newline at end of file +``` + +If you are editing the CSS, you'll also need to copy the edited CSS files. E.g. if you are editing the global/default quick-jump.css and the Linuwial theme's CSS, then + +``` +cp quick-jump.css Linuwial.std-theme/linuwial.css path-to/generated-haddock-docs +``` diff --git a/haddock-api/resources/html/haddock-bundle.min.js b/haddock-api/resources/html/haddock-bundle.min.js index 7881dc10..45adda98 100644 --- a/haddock-api/resources/html/haddock-bundle.min.js +++ b/haddock-api/resources/html/haddock-bundle.min.js @@ -1,2 +1,2 @@ -!function i(s,a,l){function c(t,e){if(!a[t]){if(!s[t]){var n="function"==typeof require&&require;if(!e&&n)return n(t,!0);if(u)return u(t,!0);var o=new Error("Cannot find module '"+t+"'");throw o.code="MODULE_NOT_FOUND",o}var r=a[t]={exports:{}};s[t][0].call(r.exports,function(e){return c(s[t][1][e]||e)},r,r.exports,i,s,a,l)}return a[t].exports}for(var u="function"==typeof require&&require,e=0;e element with id '"+e+"'");return t}function o(e){for(var t,n=e.target,o=n.id,r=u(o),i=r.element.open,s=0,a=r.toggles;swindow.innerHeight?this.searchResults.scrollTop+=e.bottom-window.innerHeight+80:e.topn)return u(e,this.pattern,o);var r=this.options,i=r.location,s=r.distance,a=r.threshold,l=r.findAllMatches,c=r.minMatchCharLength;return h(e,this.pattern,this.patternAlphabet,{location:i,distance:s,threshold:a,findAllMatches:l,minMatchCharLength:c})}}]),y}();e.exports=r},function(e,t,n){"use strict";var u=n(0);e.exports=function(e,t){return function e(t,n,o){if(n){var r=n.indexOf("."),i=n,s=null;-1!==r&&(i=n.slice(0,r),s=n.slice(r+1));var a=t[i];if(null!=a)if(s||"string"!=typeof a&&"number"!=typeof a)if(u(a))for(var l=0,c=a.length;l 0 and <= 1");p=p.name}else a[p]={weight:1};this._analyze({key:p,value:this.options.getFn(u,p),record:u,index:l},{resultMap:o,results:r,tokenSearchers:e,fullSearcher:t})}return{weights:a,results:r}}},{key:"_analyze",value:function(e,t){var n=e.key,o=e.arrayIndex,r=void 0===o?-1:o,i=e.value,s=e.record,a=e.index,l=t.tokenSearchers,c=void 0===l?[]:l,u=t.fullSearcher,h=void 0===u?[]:u,d=t.resultMap,p=void 0===d?{}:d,f=t.results,v=void 0===f?[]:f;if(null!=i){var g=!1,m=-1,y=0;if("string"==typeof i){this._log("\nKey: "+(""===n?"-":n));var _=h.search(i);if(this._log('Full text: "'+i+'", score: '+_.score),this.options.tokenize){for(var k=i.split(this.options.tokenSeparator),b=[],x=0;x=c.length;if(this._log("\nCheck Matches: "+j),(g||_.isMatch)&&j){var E=p[a];E?E.output.push({key:n,arrayIndex:r,value:i,score:I,matchedIndices:_.matchedIndices}):(p[a]={item:s,output:[{key:n,arrayIndex:r,value:i,score:I,matchedIndices:_.matchedIndices}]},v.push(p[a]))}}else if(U(i))for(var T=0,P=i.length;T element with id '"+e+"'");return t}function x(){return u.defaultInstanceState==i.Open}function w(e){for(var t=S(e.target.id),n=t.element.open,o=0,r=t.toggles;owindow.innerHeight?this.searchResults.scrollTop+=e.bottom-window.innerHeight+80:e.topn)return u(e,this.pattern,o);var r=this.options,i=r.location,s=r.distance,a=r.threshold,l=r.findAllMatches,c=r.minMatchCharLength;return d(e,this.pattern,this.patternAlphabet,{location:i,distance:s,threshold:a,findAllMatches:l,minMatchCharLength:c})}}]),y}();e.exports=r},function(e,t,n){"use strict";var u=n(0);e.exports=function(e,t){return function e(t,n,o){if(n){var r=n.indexOf("."),i=n,s=null;-1!==r&&(i=n.slice(0,r),s=n.slice(r+1));var a=t[i];if(null!=a)if(s||"string"!=typeof a&&"number"!=typeof a)if(u(a))for(var l=0,c=a.length;l 0 and <= 1");p=p.name}else a[p]={weight:1};this._analyze({key:p,value:this.options.getFn(u,p),record:u,index:l},{resultMap:o,results:r,tokenSearchers:e,fullSearcher:t})}return{weights:a,results:r}}},{key:"_analyze",value:function(e,t){var n=e.key,o=e.arrayIndex,r=void 0===o?-1:o,i=e.value,s=e.record,a=e.index,l=t.tokenSearchers,c=void 0===l?[]:l,u=t.fullSearcher,d=void 0===u?[]:u,h=t.resultMap,p=void 0===h?{}:h,f=t.results,v=void 0===f?[]:f;if(null!=i){var g=!1,m=-1,y=0;if("string"==typeof i){this._log("\nKey: "+(""===n?"-":n));var _=d.search(i);if(this._log('Full text: "'+i+'", score: '+_.score),this.options.tokenize){for(var b=i.split(this.options.tokenSeparator),k=[],S=0;S=c.length;if(this._log("\nCheck Matches: "+T),(g||_.isMatch)&&T){var N=p[a];N?N.output.push({key:n,arrayIndex:r,value:i,score:A,matchedIndices:_.matchedIndices}):(p[a]={item:s,output:[{key:n,arrayIndex:r,value:i,score:A,matchedIndices:_.matchedIndices}]},v.push(p[a]))}}else if(V(i))for(var P=0,j=i.length;P are not in their default state */ - -function lookupDetailsRegistry(id: string): DetailsInfo { - const info = detailsRegistry[id]; - if (info == undefined) { throw new Error(`could not find
element with id '${id}'`); } - return info; -} - -function onDetailsToggle(ev: Event) { - const element = ev.target as HTMLDetailsElement; - const id = element.id; - const info = lookupDetailsRegistry(id); - const isOpen = info.element.open; - for (const toggle of info.toggles) { - if (toggle.classList.contains('details-toggle-control')) { - toggle.classList.add(isOpen ? 'collapser' : 'expander'); - toggle.classList.remove(isOpen ? 'expander' : 'collapser'); - } - } - if (element.open == info.openByDefault) { - delete toggled[id]; - } else { - toggled[id] = true; - } - rememberToggled(); -} - -function gatherDetailsElements() { - const els: HTMLDetailsElement[] = Array.prototype.slice.call(document.getElementsByTagName('details')); - for (const el of els) { - if (typeof el.id == "string" && el.id.length > 0) { - detailsRegistry[el.id] = { - element: el, - openByDefault: !!el.open, - toggles: [] // added later - }; - el.addEventListener('toggle', onDetailsToggle); - } - } -} - -function toggleDetails(id: string) { - const {element} = lookupDetailsRegistry(id); - element.open = !element.open; -} - -function rememberToggled() { - const sections: string[] = Object.keys(toggled); - // cookie specific to this page; don't use setCookie which sets path=/ - document.cookie = "toggled=" + encodeURIComponent(sections.join('+')); -} - -function restoreToggled() { - const cookie = getCookie("toggled"); - if (!cookie) { return; } - const ids = cookie.split('+'); - for (const id of ids) { - const info = detailsRegistry[id]; - toggled[id] = true; - if (info) { - info.element.open = !info.element.open; - } - } -} - -function onToggleClick(ev: MouseEvent) { - ev.preventDefault(); - const toggle = ev.currentTarget as HTMLElement; - const id = toggle.getAttribute('data-details-id'); - if (!id) { throw new Error("element with class 'details-toggle' has no 'data-details-id' attribute!"); } - toggleDetails(id); -} - -function initCollapseToggles() { - const toggles: HTMLElement[] = Array.prototype.slice.call(document.getElementsByClassName('details-toggle')); - toggles.forEach(toggle => { - const id = toggle.getAttribute('data-details-id'); - if (!id) { throw new Error("element with class 'details-toggle' has no 'data-details-id' attribute!"); } - const info = lookupDetailsRegistry(id); - info.toggles.push(toggle); - toggle.addEventListener('click', onToggleClick); - if (toggle.classList.contains('details-toggle-control')) { - toggle.classList.add(info.element.open ? 'collapser' : 'expander'); - } - }); -} - -export function init() { - gatherDetailsElements(); - restoreToggled(); - initCollapseToggles(); -} \ No newline at end of file diff --git a/haddock-api/resources/html/js-src/details-helper.tsx b/haddock-api/resources/html/js-src/details-helper.tsx new file mode 100644 index 00000000..871b5417 --- /dev/null +++ b/haddock-api/resources/html/js-src/details-helper.tsx @@ -0,0 +1,464 @@ +// This file implements the UI and logic for collapsing and expanding +// instance lists ("details"). +// +// A configuration ('GlobalConfig') controlled by the UI is persisted +// in local storage in the user's browser. The configuration includes: +// +// * a global default state ('defaultInstanceState') for all instance +// lists. The possible values for the global default are "collapsed" +// and "expanded". +// +// * a global boolean option ('rememberToggles') to remember which +// specific instance lists are not in the default state (e.g. which +// instance lists are expanded when the default is "collapsed"). +// +// * a local / per-page record of which specific instance lists are +// not in the default state, when the global option +// ('rememberToggles') to remember this info is enabled. +// +// The UI consists of an Instances menu with buttons for expanding and +// collapsing all instance lists in the current module, a checkbox for +// setting the global default state, and a checkbox to enable +// remembering which instance lists are not in the global default +// state. Also, each instance list on each module page has buttons for +// collapsing and expanding. +// +// The logic of the UI is as follows: +// +// * setting the global default state erases any record of which +// specific instances are in the non-default state, and collapses or +// expands all instance lists on the current page to be in the +// global default state. +// +// * changing boolean option for remembering which specific instance +// lists are not in the default state erases any existing record of +// which instances are not in the default state across all pages, +// and updates the record for the current page when the option is +// set to true. No collapsing or expanding is done. +// +// * toggling the collapse/expand state of a specific instance list +// causes the state of that specific instance list to be recorded in +// the persisted configuration iff the new state of that specific +// instance list is different from the global default state, and the +// option to remember instance list states is enabled. There are two +// ways to toggle the collapse/expand state of a specific instance, +// by clicking its collapse/expand button, and by clicking the +// "collapse all" or "expand all" button in the Instances menu. +// +// This file also implements an association between elements (with +// class "details-toggle" and "details-toggle-control") that can be +// clicked to expand/collapse
elements, and the details +// elements themselves. Note that this covers both
elements +// that list instances -- what the above explained UI and logic is +// concerned with -- and details about individual instances themselves +// -- which the above is not concerend with. The association includes +// adding event listeners that change CSS classes back and forth +// between "expander" and "collapser"; these classes determine whether +// an element is adorned with a right arrow ("expander") or a down +// arrow ("collapser"). I don't understand why we don't directly use +// the the HTML element type to allow the
elements +// to be directly clickable. +import preact = require("preact"); + +const { h, Component } = preact; + +enum DefaultState { Closed, Open } + +interface GlobalConfig { + defaultInstanceState: DefaultState + rememberToggles: boolean +} + +// Hackage domain-wide config +const globalConfig: GlobalConfig = { + defaultInstanceState: DefaultState.Open, + rememberToggles: true, +}; + +class PreferencesButton extends Component { + render(props: { title: string, onClick: () => void }) { + function onClick(e: Event) { + e.preventDefault(); + props.onClick(); + } + return
  • {props.title}
  • ; + } +} + +function addPreferencesButton(action: () => void) { + const pageMenu = document.querySelector('#page-menu') as HTMLUListElement; + const dummy = document.createElement('li'); + pageMenu.insertBefore(dummy, pageMenu.firstChild); + preact.render(, pageMenu, dummy); +} + +type PreferencesProps = { + showHideTrigger: (action: () => void) => void +} + +type PreferencesState = { + isVisible: boolean +} + +class Preferences extends Component { + componentWillMount() { + document.addEventListener('mousedown', this.hide.bind(this)); + + document.addEventListener('keydown', (e) => { + if (this.state.isVisible) { + if (e.key === 'Escape') { + this.hide(); + } + } + }) + } + + hide() { + this.setState({ isVisible: false }); + } + + show() { + if (!this.state.isVisible) { + this.setState({ isVisible: true }); + } + } + + toggleVisibility() { + if (this.state.isVisible) { + this.hide(); + } else { + this.show(); + } + } + + componentDidMount() { + this.props.showHideTrigger(this.toggleVisibility.bind(this)); + } + + render(props: PreferencesProps, state: PreferencesState) { + const stopPropagation = (e: Event) => { e.stopPropagation(); }; + + return
    + +
    ; + } +} + +function storeGlobalConfig() { + const json = JSON.stringify(globalConfig); + try { + // https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem#Exceptions. + localStorage.setItem('global', json); + } catch (e) {} +} + +var globalConfigLoaded: boolean = false; + +function loadGlobalConfig() { + if (globalConfigLoaded) { return; } + globalConfigLoaded = true; + const global = localStorage.getItem('global'); + if (!global) { return; } + try { + const globalConfig_ = JSON.parse(global); + globalConfig.defaultInstanceState = globalConfig_.defaultInstanceState; + globalConfig.rememberToggles = globalConfig_.rememberToggles; + } catch(e) { + // Gracefully handle errors related to changed config format. + if (e instanceof SyntaxError || e instanceof TypeError) { + localStorage.removeItem('global'); + } else { + throw e; + } + } +} + +function setDefaultInstanceState(s: DefaultState) { + return (e: Event) => { + globalConfig.defaultInstanceState = s; + putInstanceListsInDefaultState(); + storeGlobalConfig(); + clearLocalStorage(); + storeLocalConfig(); + } +} + +function setRememberToggles(e: Event) { + const checked: boolean = (e as any).target.checked; + globalConfig.rememberToggles = checked; + storeGlobalConfig(); + clearLocalStorage(); + storeLocalConfig(); +} + +// Click event consumer for "default collapse" instance menu check box. +function defaultCollapseOnClick(e: Event) { + const us = document.getElementById('default-collapse-instances') as HTMLInputElement; + if (us !== null) { + if (us.checked) { + setDefaultInstanceState(DefaultState.Closed)(e); + } else { + setDefaultInstanceState(DefaultState.Open)(e); + } + } +} + +// Instances menu. +function PreferencesMenu() { + loadGlobalConfig(); + return
    +
    + + +
    +
    + + + Collapse All Instances By Default +
    +
    + + +
    +
    ; +} + +interface HTMLDetailsElement extends HTMLElement { + open: boolean +} + +interface DetailsInfo { + element: HTMLDetailsElement + // Here 'toggles' is the list of all elements of class + // 'details-toggle-control' that control toggling 'element'. I + // believe this list is always length zero or one. + toggles: HTMLElement[] +} + +// Mapping from
    elements to their info. +const detailsRegistry: { [id: string]: DetailsInfo } = {}; + +function lookupDetailsRegistry(id: string): DetailsInfo { + const info = detailsRegistry[id]; + if (info == undefined) { throw new Error(`could not find
    element with id '${id}'`); } + return info; +} + +// Return true iff instance lists are open by default. +function getDefaultOpenSetting(): boolean { + return globalConfig.defaultInstanceState == DefaultState.Open; +} + +// Event handler for "toggle" events, which are triggered when a +//
    element's "open" property changes. We don't deal with +// any config stuff here, because we only change configs in response +// to mouse clicks. In contrast, for example, this event is triggred +// automatically once for every
    element when the user clicks +// the "collapse all elements" button. +function onToggleEvent(ev: Event) { + const element = ev.target as HTMLDetailsElement; + const id = element.id; + const info = lookupDetailsRegistry(id); + const isOpen = info.element.open; + // Update the CSS of the toggle element users can click on to toggle + // 'element'. The "collapser" and "expander" classes control what + // kind of arrow appears next to the 'toggle' element. + for (const toggle of info.toggles) { + if (toggle.classList.contains('details-toggle-control')) { + toggle.classList.add(isOpen ? 'collapser' : 'expander'); + toggle.classList.remove(isOpen ? 'expander' : 'collapser'); + } + } +} + +function gatherDetailsElements() { + const els: HTMLDetailsElement[] = Array.prototype.slice.call(document.getElementsByTagName('details')); + for (const el of els) { + if (typeof el.id == "string" && el.id.length > 0) { + detailsRegistry[el.id] = { + element: el, + toggles: [] // Populated later by 'initCollapseToggles'. + }; + el.addEventListener('toggle', onToggleEvent); + } + } +} + +// Return the id of the
    element that the given 'toggle' +// element toggles. +function getDataDetailsId(toggle: Element): string { + const id = toggle.getAttribute('data-details-id'); + if (!id) { throw new Error("element with class " + toggle + " has no 'data-details-id' attribute!"); } + return id; +} + +// Toggle the "open" state of a
    element when that element's +// toggle element is clicked. +function toggleDetails(toggle: Element) { + const id = getDataDetailsId(toggle); + const {element} = lookupDetailsRegistry(id); + element.open = !element.open; +} + +// Prefix for local keys used with local storage. Idea is that other +// modules could also use local storage with a different prefix and we +// wouldn't step on each other's toes. +// +// NOTE: we're using the browser's "local storage" API via the +// 'localStorage' object to store both "local" (to the current Haddock +// page) and "global" (across all Haddock pages) configuration. Be +// aware of these two different uses of the term "local". +const localStoragePrefix: string = "local-details-config:"; + +// Local storage key for the current page. +function localStorageKey(): string { + return localStoragePrefix + document.location.pathname; +} + +// Clear all local storage related to instance list configs. +function clearLocalStorage() { + const keysToDelete: string[] = []; + for (var i = 0; i < localStorage.length; ++i) { + const key = localStorage.key(i); + if (key !== null && key.startsWith(localStoragePrefix)) { + keysToDelete.push(key); + } + } + keysToDelete.forEach(key => { + localStorage.removeItem(key); + }); +} + +// Compute and save the set of instance list ids that aren't in the +// default state. +function storeLocalConfig() { + if (!globalConfig.rememberToggles) return; + const instanceListToggles: HTMLElement[] = + // Restrict to 'details-toggle' elements for "instances" + // *plural*. These are the toggles that control instance lists and + // not the list of methods for individual instances. + Array.prototype.slice.call(document.getElementsByClassName( + 'instances details-toggle details-toggle-control')); + const nonDefaultInstanceListIds: string[] = []; + instanceListToggles.forEach(toggle => { + const id = getDataDetailsId(toggle); + const details = document.getElementById(id) as HTMLDetailsElement; + if (details.open != getDefaultOpenSetting()) { + nonDefaultInstanceListIds.push(id); + } + }); + + const json = JSON.stringify(nonDefaultInstanceListIds); + try { + // https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem#Exceptions. + localStorage.setItem(localStorageKey(), json); + } catch (e) {} +} + +function putInstanceListsInDefaultState() { + switch (globalConfig.defaultInstanceState) { + case DefaultState.Closed: _collapseAllInstances(true); break; + case DefaultState.Open: _collapseAllInstances(false); break; + default: break; + } +} + +// Expand and collapse instance lists according to global and local +// config. +function restoreToggled() { + loadGlobalConfig(); + putInstanceListsInDefaultState(); + if (!globalConfig.rememberToggles) { return; } + const local = localStorage.getItem(localStorageKey()); + if (!local) { return; } + try { + const nonDefaultInstanceListIds: string[] = JSON.parse(local); + nonDefaultInstanceListIds.forEach(id => { + const info = lookupDetailsRegistry(id); + info.element.open = ! getDefaultOpenSetting(); + }); + } catch(e) { + // Gracefully handle errors related to changed config format. + if (e instanceof SyntaxError || e instanceof TypeError) { + localStorage.removeItem(localStorageKey()); + } else { + throw e; + } + } +} + +// Handler for clicking on the "toggle" element that toggles the +//
    element with id given by the 'data-details-id' property +// of the "toggle" element. +function onToggleClick(ev: MouseEvent) { + ev.preventDefault(); + const toggle = ev.currentTarget as HTMLElement; + toggleDetails(toggle); + storeLocalConfig(); +} + +// Set event handlers on elements responsible for expanding and +// collapsing
    elements. +// +// This applies to all 'details-toggle's, not just to to top-level +// 'details-toggle's that control instance lists. +function initCollapseToggles() { + const toggles: HTMLElement[] = Array.prototype.slice.call(document.getElementsByClassName('details-toggle')); + toggles.forEach(toggle => { + const id = getDataDetailsId(toggle); + const info = lookupDetailsRegistry(id); + info.toggles.push(toggle); + toggle.addEventListener('click', onToggleClick); + if (toggle.classList.contains('details-toggle-control')) { + toggle.classList.add(info.element.open ? 'collapser' : 'expander'); + } + }); +} + +// Collapse or expand all instances. +function _collapseAllInstances(collapse: boolean) { + const ilists = document.getElementsByClassName('subs instances'); + [].forEach.call(ilists, function (ilist : Element) { + const toggleType = collapse ? 'collapser' : 'expander'; + const toggle = ilist.getElementsByClassName('instances ' + toggleType)[0]; + if (toggle) { + toggleDetails(toggle); + } + }); +} + +function collapseAllInstances() { + _collapseAllInstances(true); + storeLocalConfig(); +} + +function expandAllInstances() { + _collapseAllInstances(false); + storeLocalConfig(); +} + +export function init(showHide?: (action: () => void) => void) { + gatherDetailsElements(); + initCollapseToggles(); + restoreToggled(); + preact.render( + , + document.body + ); +} diff --git a/haddock-api/resources/html/js-src/init.ts b/haddock-api/resources/html/js-src/init.ts index 877874ae..1bfa8b3c 100644 --- a/haddock-api/resources/html/js-src/init.ts +++ b/haddock-api/resources/html/js-src/init.ts @@ -17,6 +17,6 @@ function onDomReady(callback: () => void) { onDomReady(() => { document.body.classList.add('js-enabled'); styleMenu.init(); - detailsHelper.init(); quickJump.init(); -}); \ No newline at end of file + detailsHelper.init(); +}); diff --git a/haddock-api/resources/html/js-src/style-menu.tsx b/haddock-api/resources/html/js-src/style-menu.tsx index bab840ca..2eb8344e 100644 --- a/haddock-api/resources/html/js-src/style-menu.tsx +++ b/haddock-api/resources/html/js-src/style-menu.tsx @@ -4,91 +4,14 @@ import {getCookie, setCookie, clearCookie} from "./cookies"; import preact = require("preact"); const { h, Component } = preact; -const rspace = /\s\s+/g, - rtrim = /^\s+|\s+$/g; - -function spaced(s: string) { return (" " + s + " ").replace(rspace, " "); } -function trim(s: string) { return s.replace(rtrim, ""); } - -function hasClass(elem: Element, value: string) { - const className = spaced(elem.className || ""); - return className.indexOf( " " + value + " " ) >= 0; -} - -function addClass(elem: Element, value: string) { - const className = spaced(elem.className || ""); - if ( className.indexOf( " " + value + " " ) < 0 ) { - elem.className = trim(className + " " + value); - } -} - -function removeClass(elem: Element, value: string) { - let className = spaced(elem.className || ""); - className = className.replace(" " + value + " ", " "); - elem.className = trim(className); -} - -function toggleClass(elem: Element, valueOn: string, valueOff: string, bool?: boolean): boolean { - if (bool == null) { bool = ! hasClass(elem, valueOn); } - if (bool) { - removeClass(elem, valueOff); - addClass(elem, valueOn); - } - else { - removeClass(elem, valueOn); - addClass(elem, valueOff); - } - return bool; -} - -function makeClassToggle(valueOn: string, valueOff: string): (elem: Element, bool?: boolean) => boolean { - return function(elem, bool) { - return toggleClass(elem, valueOn, valueOff, bool); - } -} - -const toggleShow = makeClassToggle("show", "hide"); +// Get all of the styles that are available function styles(): HTMLLinkElement[] { const es = Array.prototype.slice.call(document.getElementsByTagName("link")); return es.filter((a: HTMLLinkElement) => a.rel.indexOf("style") != -1 && a.title); } -class StyleMenuButton extends Component { - - render(props: { stys: string[] }) { - function action() { - styleMenu(); - return false; - }; - - return
  • - Style ▾ -
      - {props.stys.map((sty) => { - function action() { - setActiveStyleSheet(sty); - return false; - }; - - return
    • {sty}
    • ; - })} -
    -
  • ; - } - -} - -function addStyleMenu() { - const stys = styles().map((s) => s.title); - if (stys.length > 1) { - const pageMenu = document.querySelector('#page-menu') as HTMLUListElement; - const dummy = document.createElement('li'); - pageMenu.appendChild(dummy); - preact.render(, pageMenu, dummy); - } -} - +// Set a style (including setting the cookie) function setActiveStyleSheet(title: string) { const as = styles(); let found: null | HTMLLinkElement = null; @@ -110,17 +33,103 @@ function setActiveStyleSheet(title: string) { } } +// Reset the style based on the cookie function resetStyle() { const s = getCookie("haddock-style"); if (s) setActiveStyleSheet(s); } -function styleMenu(show?: boolean) { - const m = document.getElementById('style-menu'); - if (m) toggleShow(m, show); +class StylesButton extends Component { + render(props: { title: string, onClick: () => void }) { + function onClick(e: Event) { + e.preventDefault(); + props.onClick(); + } + return
  • {props.title}
  • ; + } } -export function init() { - addStyleMenu(); +// Add the style menu button +function addStyleMenu(stys: string[], action: () => void) { + if (stys.length > 1) { + const pageMenu = document.querySelector('#page-menu') as HTMLUListElement; + const dummy = document.createElement('li'); + pageMenu.appendChild(dummy); + preact.render(, pageMenu, dummy); + } +} + +type StyleProps = { + styles: string[] + showHideTrigger: (action: () => void) => void +} + +type StyleState = { + isVisible: boolean +} + +// Represents the full style dropdown +class Styles extends Component { + + componentWillMount() { + document.addEventListener('mousedown', this.hide.bind(this)); + + document.addEventListener('keydown', (e) => { + if (this.state.isVisible) { + if (e.key === 'Escape') { + this.hide(); + } + } + }) + } + + hide() { + this.setState({ isVisible: false }); + } + + show() { + if (!this.state.isVisible) { + this.setState({ isVisible: true }); + } + } + + toggleVisibility() { + if (this.state.isVisible) { + this.hide(); + } else { + this.show(); + } + } + + componentDidMount() { + this.props.showHideTrigger(this.toggleVisibility.bind(this)); + } + + render(props: StyleProps, state: StyleState) { + const stopPropagation = (e: Event) => { e.stopPropagation(); }; + + return
    + +
    ; + } +} + + +export function init(showHide?: (action: () => void) => void) { + const stys = styles().map((s) => s.title); + const addStylesButton = (action: () => void) => addStyleMenu(stys, action) resetStyle(); + preact.render( + , + document.body + ); } diff --git a/haddock-api/resources/html/quick-jump.css b/haddock-api/resources/html/quick-jump.css index 468d8036..8772809c 100644 --- a/haddock-api/resources/html/quick-jump.css +++ b/haddock-api/resources/html/quick-jump.css @@ -1,3 +1,11 @@ +/* @group Fundamentals */ + +.hidden { + display: none; +} + +/* @end */ + /* @group Search box layout */ #search { @@ -11,8 +19,10 @@ overflow-y: auto; } -#search.hidden { - display: none; +@media only screen and (max-width: 999px) { + #search { + top: 5.7em; + } } #search-form, #search-results { @@ -162,3 +172,49 @@ } /* @end */ + +/* @group Dropdown menus */ + +/* Based on #search styling above. */ + +.dropdown-menu { + position: fixed; + /* Not robust to window size changes. */ + top: 3.2em; + right: 0; + /* To display on top of synopsis menu on right side. */ + z-index: 1000; + border: 0.05em solid #b2d5fb; + background: #e8f3ff; +} + +@media only screen and (max-width: 999px) { + .dropdown-menu { + top: 5.7em; + } +} + +.dropdown-menu * { + margin: 0.1em; +} + +.dropdown-menu button { + border: 1px #5E5184 solid; + border-radius: 3px; + background: #5E5184; + padding: 3px; + color: #f4f4f4; + min-width: 6em; +} + +.dropdown-menu button:hover { + color: #5E5184; + background: #f4f4f4; +} + +.dropdown-menu button:active { + color: #f4f4f4; + background: #5E5184; +} + +/* @end */ -- cgit v1.2.3