repo
stringlengths
5
75
commit
stringlengths
40
40
message
stringlengths
6
18.2k
diff
stringlengths
60
262k
dotjay/hashgrid
152a14824fc9b3b10b4c50f1ace3b05c8709852b
Correct link to Sean Coates
diff --git a/index.html b/index.html index 6eb979c..fc4583c 100644 --- a/index.html +++ b/index.html @@ -1,317 +1,317 @@ <!DOCTYPE html><html lang="en-GB"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><link rel="shortcut icon" type="image/x-icon" href="favicon.ico"><title>#grid</title> <!-- Demo styles--> <style type="text/css"> /* Putting inline rules here so the document can be downloaded with style */ body{ font-size: 1em; line-height: 1.25; font-family: Arial, sans-serif; background: White; color: DimGray; margin: 0; padding: 0 20px; } #content{ font-size: 16px; line-height: 20px; position: relative; } #content{ width: 620px; margin: 0 auto; } #footer{ border-top: 1px dotted DarkGray; padding-top: 19px; } h1, h2{ color: Black; font-weight: normal; } h1{ font-size: 36px; line-height: 40px; margin: 40px 0 20px; padding-bottom: 19px; border-bottom: 1px dotted DarkGray; } h1 em{ font-style: normal; color: DarkGray; font-size: 16px; line-height: 20px; margin: 0 0 20px; } h2, h3{ font-size: 16px; font-weight: 700; line-height: 20px; margin: 0 0 20px; } h3{ font-weight: 300; } a:link, a:visited{ color: Black; text-decoration: none; padding: 0 2px; background-color: WhiteSmoke; border-bottom: 1px solid Gold; } a:focus{ outline: none; } a:focus, a:hover, a:active{ background-color: Khaki; border-bottom: 1px solid GoldenRod; } p, ul{ padding: 0; margin: 0 0 20px; } dl, ol{ padding: 0; margin: 0; } ul{ list-style: circle; } ol li{ margin-bottom: 20px; } dd{ margin: 0 0 20px 0; } del{ text-decoration: line-through; opacity: 0.75; } ins{ text-decoration: none; } code{ font-size: 14px; line-height: 1; } textarea{ font-family: 'Courier New', monospace; font-size: 14px; line-height: 20px; display: block; width: 600px; margin: 0 0 20px; padding: 20px 0 0 15px; border: 0; color: Black; background: Gainsboro; border-left: 5px solid DarkGray; } #javascript-code{ height: 300px; } #css-code{ height: 1560px; } .summary em{ font-style: normal; position: absolute; color: DarkGray; right: 0; top: 18px; width: 140px; } .summary em span{ position: absolute; left: -9999px; } #download{ line-height: 60px; padding: 0 40px 0 15px; border-left: 5px solid DarkGray; background: Gainsboro; color: DimGray; } span.key{ color: Black; text-transform: uppercase; } </style> <!-- Hashgrid styles--> <style type="text/css"> /** * Hashgrid */ #grid{ /* * Spreads the whole page by default * Adjust to match your container */ /*width: 100%;*/ width: 980px; position: absolute; height: 100%; top: 0; left: 50%; margin-left: -490px; overflow: hidden; } .hashgrid-column-container { position: absolute; height: 100%; width: 100%; top: 0; left: 0; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ .hashgrid__column{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-left: 19px; height: 100%; float: left; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ .hashgrid__row{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option when instantiating Hashgrid. * e.g. * * var hg = new Hashgrid({ * numberOfGrids: 2 * }); */ #hashgrid.hashgrid2, #hashgrid.hashgrid2 .hashgrid-column-container{ /* Container width adjustments */ padding: 0 160px; width: 660px; } #hashgrid.hashgrid2 .hashgrid__column{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </style> </head><body><main id="content"><h1>#grid&nbsp;<em>v10</em></h1><p class="summary"><em>30 Nov 2015<span>:</span></em>#grid (or “Hashgrid”) is a little tool that inserts a&#160;<a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a>&nbsp;in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit&nbsp;<span class="key">g</span> on your keyboard.</p><h2>Download</h2><p id="download"><a href="https://github.com/dotjay/hashgrid/tags">Download #grid</a>&nbsp;from&nbsp;<a href="https://github.com/dotjay/hashgrid">GitHub</a></p><h2 id="features">Features</h2><ul><li>Adaptable for all layout widths and alignments</li><li>Adaptable for any vertical rhythm value</li><li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li><li>Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters</li></ul><p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p><h2 id="installation">Installation</h2><ol><li><h3>Copy the&nbsp;<a href="https://github.com/dotjay/hashgrid/tree/main/dist/javascripts">hashgrid.js</a>&nbsp;script to your project</h3></li><li><h3>Add this script to your page(s) just before the closing <code>&#60;/body&#62;</code> tag</h3><textarea id="javascript-code" cols="68" rows="15" readonly="readonly">&#60;!-- Include the hashgrid script --&#62; &#60;script type="text/javascript" src="hashgrid.js"&#62;&#60;/script&#62; &#60;!-- Kick hashgrid into action --&#62; &#60;script type="text/javascript"&#62; var grid = new Hashgrid({ numberOfGrids: 2 }); &#60;/script&#62; &#60;!-- Note: Use window onload if your css is not inlined --&#62; &#60;script type="text/javascript"&#62; window.addEventListener("load", function(event) { var grid = new Hashgrid({ numberOfGrids: 2 }); }); &#60;/script&#62;</textarea></li><li><h3>Add the CSS to your page(s)</h3><textarea id="css-code" cols="68" rows="64" readonly="readonly">/** * Grid */ #hashgrid{ /* * Spreads the whole page by default * Adjust to match your container */ /*width: 100%;*/ width: 980px; position: absolute; height: 100%; top: 0; left: 50%; margin-left: -490px; overflow: hidden; } .hashgrid-column-container { position: absolute; height: 100%; width: 100%; top: 0; left: 0; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ .hashgrid__column{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-left: 19px; height: 100%; float: left; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ .hashgrid__row{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option when instantiating hashgrid. * e.g. * * var hg = new Hashgrid({ * numberOfGrids: 2 * }); */ #hashgrid.hashgrid2, #hashgrid.hashgrid2 .hashgrid-column-container{ /* Container width adjustments */ padding: 0 160px; width: 660px; } #hashgrid.hashgrid2 .hashgrid__column{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } -</textarea></li><li><h3>Modify #grid to suit your needs</h3><p>The CSS and JavaScript is annotated to help you.</p></li></ol><h2 id="usage">Usage</h2><p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p><dl><dt><span class="key">g</span></dt><dd>Show the grid until you release.</dd><dt><span class="key">g</span> + <span class="key">h</span></dt><dd>Show and hold the grid (<span class="key">g</span> will remove it again).</dd><dt><span class="key">g</span> + <span class="key">f</span></dt><dd>Toggle the grid to the foreground and back. Pressing <span class="key">f</span> while the grid is held also works.</dd><dt><span class="key">g</span> + <span class="key">j</span></dt><dd>Jump to the next grid. Pressing <span class="key">j</span> while the grid is held also works.</dd></dl><p><em>Note: Hashgrid remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em></p><h2 id="release-notes">Release Notes</h2><dl><dt>v10&#8201;&#8212;&#8201;30 Nov 2015</dt><dd>Works with vanilla JavaScript - jQuery is no longer required - thanks to <a href="https://github.com/widatama">widatama</a>.</dd><dt>v9&#8201;&#8212;&#8201;30 May 2013</dt><dd>Minor release: Improved example usage to avoid conflicts.</dd><dt>v8&#8201;&#8212;&#8201;6 Oct 2012</dt><dd><ul><li>Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="http://www.tomarnold.de/">Tom Arnold</a>.</li><li>Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="https://github.com/callumacrae">Callum Macrae</a>.</li><li>Fixes to cookie handling. Thanks to <a href="http://loonypandora.co.uk/">James Aitken</a>.</li><li>Optimisations.</li></ul></dd><dt>v7&#8201;&#8212;&#8201;11 Jun 2011</dt><dd>Minor release: Updated license references.</dd><dt>v6&#8201;&#8212;&#8201;10 Jun 2011</dt><dd>Minor release: Optimisations (thanks to <a href="https://github.com/ajaswa/">Andrew Jaswa</a> for contributions), and now released under an Apache License.</dd><dt>v5&#8201;&#8212;&#8201;3 Nov 2010</dt><dd><ul><li>Vertical grid lines can now be set using CSS&#8230; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution.</li><li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li><li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback.</li></ul></dd><dt>v4&#8201;&#8212;&#8201;29 Mar 2010</dt><dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd><dt>v3&#8201;&#8212;&#8201;22 Feb 2010</dt><dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd><dt>v2&#8201;&#8212;&#8201;2 Feb 2010</dt><dd><ul><li>Keys are now more easily configured (see top of hashgrid.js).</li><li>Fixed crash when using with disabled CSS.</li><li>Renamed the GridOverlay object to hashgrid.</li></ul></dd><dt>v1&#8201;&#8212;&#8201;21 Dec 2009</dt><dd>First release.</dd></dl><h2 id="known-issues">Known Issues</h2><ul><li>No known issues.</li></ul><h2 id="license">License</h2><p>Copyright 2013-2022 Jon Gibbins</p><p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br/></p><a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a><p><br/>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.</p><p>This essentially means that you&#8217;re free to copy, modify and distribute it for any project so long as you provide clear attribution to the author. <a href="https://dotjay.com/contact">Get in touch</a> if you need a different license.</p><div id="footer" role="contentinfo"><p>#grid was built by <a href="https://dotjay.com/">Jon Gibbins</a> and designed by <a href="https://jontangerine.com/">Jon Tan</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p></div></main><!-- Include the hashgrid script--><script type="text/javascript" src="dist/javascripts/hashgrid.js"></script><!-- Kick hashgrid into action--><script>var hg = new Hashgrid({ +</textarea></li><li><h3>Modify #grid to suit your needs</h3><p>The CSS and JavaScript is annotated to help you.</p></li></ol><h2 id="usage">Usage</h2><p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p><dl><dt><span class="key">g</span></dt><dd>Show the grid until you release.</dd><dt><span class="key">g</span> + <span class="key">h</span></dt><dd>Show and hold the grid (<span class="key">g</span> will remove it again).</dd><dt><span class="key">g</span> + <span class="key">f</span></dt><dd>Toggle the grid to the foreground and back. Pressing <span class="key">f</span> while the grid is held also works.</dd><dt><span class="key">g</span> + <span class="key">j</span></dt><dd>Jump to the next grid. Pressing <span class="key">j</span> while the grid is held also works.</dd></dl><p><em>Note: Hashgrid remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em></p><h2 id="release-notes">Release Notes</h2><dl><dt>v10&#8201;&#8212;&#8201;30 Nov 2015</dt><dd>Works with vanilla JavaScript - jQuery is no longer required - thanks to <a href="https://github.com/widatama">widatama</a>.</dd><dt>v9&#8201;&#8212;&#8201;30 May 2013</dt><dd>Minor release: Improved example usage to avoid conflicts.</dd><dt>v8&#8201;&#8212;&#8201;6 Oct 2012</dt><dd><ul><li>Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="http://www.tomarnold.de/">Tom Arnold</a>.</li><li>Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="https://github.com/callumacrae">Callum Macrae</a>.</li><li>Fixes to cookie handling. Thanks to <a href="http://loonypandora.co.uk/">James Aitken</a>.</li><li>Optimisations.</li></ul></dd><dt>v7&#8201;&#8212;&#8201;11 Jun 2011</dt><dd>Minor release: Updated license references.</dd><dt>v6&#8201;&#8212;&#8201;10 Jun 2011</dt><dd>Minor release: Optimisations (thanks to <a href="https://github.com/ajaswa/">Andrew Jaswa</a> for contributions), and now released under an Apache License.</dd><dt>v5&#8201;&#8212;&#8201;3 Nov 2010</dt><dd><ul><li>Vertical grid lines can now be set using CSS&#8230; images are no longer required! Thanks to <a href="https://twitter.com/coates">Sean Coates</a> for the contribution.</li><li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li><li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback.</li></ul></dd><dt>v4&#8201;&#8212;&#8201;29 Mar 2010</dt><dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd><dt>v3&#8201;&#8212;&#8201;22 Feb 2010</dt><dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd><dt>v2&#8201;&#8212;&#8201;2 Feb 2010</dt><dd><ul><li>Keys are now more easily configured (see top of hashgrid.js).</li><li>Fixed crash when using with disabled CSS.</li><li>Renamed the GridOverlay object to hashgrid.</li></ul></dd><dt>v1&#8201;&#8212;&#8201;21 Dec 2009</dt><dd>First release.</dd></dl><h2 id="known-issues">Known Issues</h2><ul><li>No known issues.</li></ul><h2 id="license">License</h2><p>Copyright 2013-2022 Jon Gibbins</p><p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br/></p><a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a><p><br/>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.</p><p>This essentially means that you&#8217;re free to copy, modify and distribute it for any project so long as you provide clear attribution to the author. <a href="https://dotjay.com/contact">Get in touch</a> if you need a different license.</p><div id="footer" role="contentinfo"><p>#grid was built by <a href="https://dotjay.com/">Jon Gibbins</a> and designed by <a href="https://jontangerine.com/">Jon Tan</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p></div></main><!-- Include the hashgrid script--><script type="text/javascript" src="dist/javascripts/hashgrid.js"></script><!-- Kick hashgrid into action--><script>var hg = new Hashgrid({ numberOfGrids: 2 });</script></body></html> \ No newline at end of file diff --git a/src/index.jade b/src/index.jade index b961bc5..3cdd17d 100644 --- a/src/index.jade +++ b/src/index.jade @@ -1,157 +1,157 @@ doctype html html(lang="en-GB") head meta(http-equiv="Content-Type", content="text/html; charset=utf-8") link(rel="shortcut icon", type="image/x-icon", href="favicon.ico") title #grid // Demo styles style(type="text/css") include ./partial/demo.css // Hashgrid styles style(type="text/css") include ./partial/hashgrid.css body main#content h1 | #grid&nbsp; em v10 p.summary em 30 Nov 2015 span : | #grid (or “Hashgrid”) is a little tool that inserts a&#160; a(href="http://en.wikipedia.org/wiki/Grid_(page_layout)") layout grid | &nbsp;in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit&nbsp; span(class="key") g | on your keyboard. h2 Download p#download a(href="https://github.com/dotjay/hashgrid/tags") Download #grid | &nbsp;from&nbsp; a(href="https://github.com/dotjay/hashgrid") GitHub h2#features Features ul li Adaptable for all layout widths and alignments li Adaptable for any vertical rhythm value li Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids li Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters p #grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids. h2#installation Installation ol li h3 Copy the&nbsp; a(href="https://github.com/dotjay/hashgrid/tree/main/dist/javascripts") hashgrid.js | &nbsp;script to your project li h3 Add this script to your page(s) just before the closing <code>&#60;/body&#62;</code> tag include ./partial/js_code.jade li h3 Add the CSS to your page(s) include ./partial/css_code.jade li h3 Modify #grid to suit your needs p The CSS and JavaScript is annotated to help you. h2#usage Usage p The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first. dl dt <span class="key">g</span> dd Show the grid until you release. dt <span class="key">g</span> + <span class="key">h</span> dd Show and hold the grid (<span class="key">g</span> will remove it again). dt <span class="key">g</span> + <span class="key">f</span> dd Toggle the grid to the foreground and back. Pressing <span class="key">f</span> while the grid is held also works. dt <span class="key">g</span> + <span class="key">j</span> dd Jump to the next grid. Pressing <span class="key">j</span> while the grid is held also works. p <em>Note: Hashgrid remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em> h2#release-notes Release Notes dl dt v10&#8201;&#8212;&#8201;30 Nov 2015 dd Works with vanilla JavaScript - jQuery is no longer required - thanks to <a href="https://github.com/widatama">widatama</a>. dt v9&#8201;&#8212;&#8201;30 May 2013 dd Minor release: Improved example usage to avoid conflicts. dt v8&#8201;&#8212;&#8201;6 Oct 2012 dd ul li Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="http://www.tomarnold.de/">Tom Arnold</a>. li Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="https://github.com/callumacrae">Callum Macrae</a>. li Fixes to cookie handling. Thanks to <a href="http://loonypandora.co.uk/">James Aitken</a>. li Optimisations. dt v7&#8201;&#8212;&#8201;11 Jun 2011 dd Minor release: Updated license references. dt v6&#8201;&#8212;&#8201;10 Jun 2011 dd Minor release: Optimisations (thanks to <a href="https://github.com/ajaswa/">Andrew Jaswa</a> for contributions), and now released under an Apache License. dt v5&#8201;&#8212;&#8201;3 Nov 2010 dd ul - li Vertical grid lines can now be set using CSS&#8230; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution. + li Vertical grid lines can now be set using CSS&#8230; images are no longer required! Thanks to <a href="https://twitter.com/coates">Sean Coates</a> for the contribution. li Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property. li Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback. dt v4&#8201;&#8212;&#8201;29 Mar 2010 dd Fixes for multiple grid support under WebKit (Safari and Chrome). dt v3&#8201;&#8212;&#8201;22 Feb 2010 dd Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms. dt v2&#8201;&#8212;&#8201;2 Feb 2010 dd ul li Keys are now more easily configured (see top of hashgrid.js). li Fixed crash when using with disabled CSS. li Renamed the GridOverlay object to hashgrid. dt v1&#8201;&#8212;&#8201;21 Dec 2009 dd First release. h2#known-issues Known Issues ul li No known issues. h2#license License p Copyright 2013-2022 Jon Gibbins p Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br/> a(href="http://www.apache.org/licenses/LICENSE-2.0") http://www.apache.org/licenses/LICENSE-2.0 p <br/>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. p This essentially means that you&#8217;re free to copy, modify and distribute it for any project so long as you provide clear attribution to the author. <a href="https://dotjay.com/contact">Get in touch</a> if you need a different license. div#footer(role="contentinfo") p #grid was built by <a href="https://dotjay.com/">Jon Gibbins</a> and designed by <a href="https://jontangerine.com/">Jon Tan</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only. // Include the Hashgrid script script(type="text/javascript" src="dist/javascripts/hashgrid.js") // Kick Hashgrid into action script. var hg = new Hashgrid({ numberOfGrids: 2 });
dotjay/hashgrid
5d5b4ff5ae22423d17f23401b6a99ee0550d462d
Correct link to Andrew Jaswa
diff --git a/index.html b/index.html index 9b07fa0..6eb979c 100644 --- a/index.html +++ b/index.html @@ -1,317 +1,317 @@ <!DOCTYPE html><html lang="en-GB"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><link rel="shortcut icon" type="image/x-icon" href="favicon.ico"><title>#grid</title> <!-- Demo styles--> <style type="text/css"> /* Putting inline rules here so the document can be downloaded with style */ body{ font-size: 1em; line-height: 1.25; font-family: Arial, sans-serif; background: White; color: DimGray; margin: 0; padding: 0 20px; } #content{ font-size: 16px; line-height: 20px; position: relative; } #content{ width: 620px; margin: 0 auto; } #footer{ border-top: 1px dotted DarkGray; padding-top: 19px; } h1, h2{ color: Black; font-weight: normal; } h1{ font-size: 36px; line-height: 40px; margin: 40px 0 20px; padding-bottom: 19px; border-bottom: 1px dotted DarkGray; } h1 em{ font-style: normal; color: DarkGray; font-size: 16px; line-height: 20px; margin: 0 0 20px; } h2, h3{ font-size: 16px; font-weight: 700; line-height: 20px; margin: 0 0 20px; } h3{ font-weight: 300; } a:link, a:visited{ color: Black; text-decoration: none; padding: 0 2px; background-color: WhiteSmoke; border-bottom: 1px solid Gold; } a:focus{ outline: none; } a:focus, a:hover, a:active{ background-color: Khaki; border-bottom: 1px solid GoldenRod; } p, ul{ padding: 0; margin: 0 0 20px; } dl, ol{ padding: 0; margin: 0; } ul{ list-style: circle; } ol li{ margin-bottom: 20px; } dd{ margin: 0 0 20px 0; } del{ text-decoration: line-through; opacity: 0.75; } ins{ text-decoration: none; } code{ font-size: 14px; line-height: 1; } textarea{ font-family: 'Courier New', monospace; font-size: 14px; line-height: 20px; display: block; width: 600px; margin: 0 0 20px; padding: 20px 0 0 15px; border: 0; color: Black; background: Gainsboro; border-left: 5px solid DarkGray; } #javascript-code{ height: 300px; } #css-code{ height: 1560px; } .summary em{ font-style: normal; position: absolute; color: DarkGray; right: 0; top: 18px; width: 140px; } .summary em span{ position: absolute; left: -9999px; } #download{ line-height: 60px; padding: 0 40px 0 15px; border-left: 5px solid DarkGray; background: Gainsboro; color: DimGray; } span.key{ color: Black; text-transform: uppercase; } </style> <!-- Hashgrid styles--> <style type="text/css"> /** * Hashgrid */ #grid{ /* * Spreads the whole page by default * Adjust to match your container */ /*width: 100%;*/ width: 980px; position: absolute; height: 100%; top: 0; left: 50%; margin-left: -490px; overflow: hidden; } .hashgrid-column-container { position: absolute; height: 100%; width: 100%; top: 0; left: 0; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ .hashgrid__column{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-left: 19px; height: 100%; float: left; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ .hashgrid__row{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option when instantiating Hashgrid. * e.g. * * var hg = new Hashgrid({ * numberOfGrids: 2 * }); */ #hashgrid.hashgrid2, #hashgrid.hashgrid2 .hashgrid-column-container{ /* Container width adjustments */ padding: 0 160px; width: 660px; } #hashgrid.hashgrid2 .hashgrid__column{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </style> </head><body><main id="content"><h1>#grid&nbsp;<em>v10</em></h1><p class="summary"><em>30 Nov 2015<span>:</span></em>#grid (or “Hashgrid”) is a little tool that inserts a&#160;<a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a>&nbsp;in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit&nbsp;<span class="key">g</span> on your keyboard.</p><h2>Download</h2><p id="download"><a href="https://github.com/dotjay/hashgrid/tags">Download #grid</a>&nbsp;from&nbsp;<a href="https://github.com/dotjay/hashgrid">GitHub</a></p><h2 id="features">Features</h2><ul><li>Adaptable for all layout widths and alignments</li><li>Adaptable for any vertical rhythm value</li><li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li><li>Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters</li></ul><p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p><h2 id="installation">Installation</h2><ol><li><h3>Copy the&nbsp;<a href="https://github.com/dotjay/hashgrid/tree/main/dist/javascripts">hashgrid.js</a>&nbsp;script to your project</h3></li><li><h3>Add this script to your page(s) just before the closing <code>&#60;/body&#62;</code> tag</h3><textarea id="javascript-code" cols="68" rows="15" readonly="readonly">&#60;!-- Include the hashgrid script --&#62; &#60;script type="text/javascript" src="hashgrid.js"&#62;&#60;/script&#62; &#60;!-- Kick hashgrid into action --&#62; &#60;script type="text/javascript"&#62; var grid = new Hashgrid({ numberOfGrids: 2 }); &#60;/script&#62; &#60;!-- Note: Use window onload if your css is not inlined --&#62; &#60;script type="text/javascript"&#62; window.addEventListener("load", function(event) { var grid = new Hashgrid({ numberOfGrids: 2 }); }); &#60;/script&#62;</textarea></li><li><h3>Add the CSS to your page(s)</h3><textarea id="css-code" cols="68" rows="64" readonly="readonly">/** * Grid */ #hashgrid{ /* * Spreads the whole page by default * Adjust to match your container */ /*width: 100%;*/ width: 980px; position: absolute; height: 100%; top: 0; left: 50%; margin-left: -490px; overflow: hidden; } .hashgrid-column-container { position: absolute; height: 100%; width: 100%; top: 0; left: 0; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ .hashgrid__column{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-left: 19px; height: 100%; float: left; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ .hashgrid__row{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option when instantiating hashgrid. * e.g. * * var hg = new Hashgrid({ * numberOfGrids: 2 * }); */ #hashgrid.hashgrid2, #hashgrid.hashgrid2 .hashgrid-column-container{ /* Container width adjustments */ padding: 0 160px; width: 660px; } #hashgrid.hashgrid2 .hashgrid__column{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } -</textarea></li><li><h3>Modify #grid to suit your needs</h3><p>The CSS and JavaScript is annotated to help you.</p></li></ol><h2 id="usage">Usage</h2><p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p><dl><dt><span class="key">g</span></dt><dd>Show the grid until you release.</dd><dt><span class="key">g</span> + <span class="key">h</span></dt><dd>Show and hold the grid (<span class="key">g</span> will remove it again).</dd><dt><span class="key">g</span> + <span class="key">f</span></dt><dd>Toggle the grid to the foreground and back. Pressing <span class="key">f</span> while the grid is held also works.</dd><dt><span class="key">g</span> + <span class="key">j</span></dt><dd>Jump to the next grid. Pressing <span class="key">j</span> while the grid is held also works.</dd></dl><p><em>Note: Hashgrid remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em></p><h2 id="release-notes">Release Notes</h2><dl><dt>v10&#8201;&#8212;&#8201;30 Nov 2015</dt><dd>Works with vanilla JavaScript - jQuery is no longer required - thanks to <a href="https://github.com/widatama">widatama</a>.</dd><dt>v9&#8201;&#8212;&#8201;30 May 2013</dt><dd>Minor release: Improved example usage to avoid conflicts.</dd><dt>v8&#8201;&#8212;&#8201;6 Oct 2012</dt><dd><ul><li>Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="http://www.tomarnold.de/">Tom Arnold</a>.</li><li>Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="https://github.com/callumacrae">Callum Macrae</a>.</li><li>Fixes to cookie handling. Thanks to <a href="http://loonypandora.co.uk/">James Aitken</a>.</li><li>Optimisations.</li></ul></dd><dt>v7&#8201;&#8212;&#8201;11 Jun 2011</dt><dd>Minor release: Updated license references.</dd><dt>v6&#8201;&#8212;&#8201;10 Jun 2011</dt><dd>Minor release: Optimisations (thanks to <a href="http://andrewjaswa.com/">Andrew Jaswa</a> for contributions), and now released under an Apache License.</dd><dt>v5&#8201;&#8212;&#8201;3 Nov 2010</dt><dd><ul><li>Vertical grid lines can now be set using CSS&#8230; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution.</li><li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li><li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback.</li></ul></dd><dt>v4&#8201;&#8212;&#8201;29 Mar 2010</dt><dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd><dt>v3&#8201;&#8212;&#8201;22 Feb 2010</dt><dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd><dt>v2&#8201;&#8212;&#8201;2 Feb 2010</dt><dd><ul><li>Keys are now more easily configured (see top of hashgrid.js).</li><li>Fixed crash when using with disabled CSS.</li><li>Renamed the GridOverlay object to hashgrid.</li></ul></dd><dt>v1&#8201;&#8212;&#8201;21 Dec 2009</dt><dd>First release.</dd></dl><h2 id="known-issues">Known Issues</h2><ul><li>No known issues.</li></ul><h2 id="license">License</h2><p>Copyright 2013-2022 Jon Gibbins</p><p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br/></p><a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a><p><br/>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.</p><p>This essentially means that you&#8217;re free to copy, modify and distribute it for any project so long as you provide clear attribution to the author. <a href="https://dotjay.com/contact">Get in touch</a> if you need a different license.</p><div id="footer" role="contentinfo"><p>#grid was built by <a href="https://dotjay.com/">Jon Gibbins</a> and designed by <a href="https://jontangerine.com/">Jon Tan</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p></div></main><!-- Include the hashgrid script--><script type="text/javascript" src="dist/javascripts/hashgrid.js"></script><!-- Kick hashgrid into action--><script>var hg = new Hashgrid({ +</textarea></li><li><h3>Modify #grid to suit your needs</h3><p>The CSS and JavaScript is annotated to help you.</p></li></ol><h2 id="usage">Usage</h2><p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p><dl><dt><span class="key">g</span></dt><dd>Show the grid until you release.</dd><dt><span class="key">g</span> + <span class="key">h</span></dt><dd>Show and hold the grid (<span class="key">g</span> will remove it again).</dd><dt><span class="key">g</span> + <span class="key">f</span></dt><dd>Toggle the grid to the foreground and back. Pressing <span class="key">f</span> while the grid is held also works.</dd><dt><span class="key">g</span> + <span class="key">j</span></dt><dd>Jump to the next grid. Pressing <span class="key">j</span> while the grid is held also works.</dd></dl><p><em>Note: Hashgrid remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em></p><h2 id="release-notes">Release Notes</h2><dl><dt>v10&#8201;&#8212;&#8201;30 Nov 2015</dt><dd>Works with vanilla JavaScript - jQuery is no longer required - thanks to <a href="https://github.com/widatama">widatama</a>.</dd><dt>v9&#8201;&#8212;&#8201;30 May 2013</dt><dd>Minor release: Improved example usage to avoid conflicts.</dd><dt>v8&#8201;&#8212;&#8201;6 Oct 2012</dt><dd><ul><li>Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="http://www.tomarnold.de/">Tom Arnold</a>.</li><li>Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="https://github.com/callumacrae">Callum Macrae</a>.</li><li>Fixes to cookie handling. Thanks to <a href="http://loonypandora.co.uk/">James Aitken</a>.</li><li>Optimisations.</li></ul></dd><dt>v7&#8201;&#8212;&#8201;11 Jun 2011</dt><dd>Minor release: Updated license references.</dd><dt>v6&#8201;&#8212;&#8201;10 Jun 2011</dt><dd>Minor release: Optimisations (thanks to <a href="https://github.com/ajaswa/">Andrew Jaswa</a> for contributions), and now released under an Apache License.</dd><dt>v5&#8201;&#8212;&#8201;3 Nov 2010</dt><dd><ul><li>Vertical grid lines can now be set using CSS&#8230; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution.</li><li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li><li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback.</li></ul></dd><dt>v4&#8201;&#8212;&#8201;29 Mar 2010</dt><dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd><dt>v3&#8201;&#8212;&#8201;22 Feb 2010</dt><dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd><dt>v2&#8201;&#8212;&#8201;2 Feb 2010</dt><dd><ul><li>Keys are now more easily configured (see top of hashgrid.js).</li><li>Fixed crash when using with disabled CSS.</li><li>Renamed the GridOverlay object to hashgrid.</li></ul></dd><dt>v1&#8201;&#8212;&#8201;21 Dec 2009</dt><dd>First release.</dd></dl><h2 id="known-issues">Known Issues</h2><ul><li>No known issues.</li></ul><h2 id="license">License</h2><p>Copyright 2013-2022 Jon Gibbins</p><p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br/></p><a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a><p><br/>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.</p><p>This essentially means that you&#8217;re free to copy, modify and distribute it for any project so long as you provide clear attribution to the author. <a href="https://dotjay.com/contact">Get in touch</a> if you need a different license.</p><div id="footer" role="contentinfo"><p>#grid was built by <a href="https://dotjay.com/">Jon Gibbins</a> and designed by <a href="https://jontangerine.com/">Jon Tan</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p></div></main><!-- Include the hashgrid script--><script type="text/javascript" src="dist/javascripts/hashgrid.js"></script><!-- Kick hashgrid into action--><script>var hg = new Hashgrid({ numberOfGrids: 2 });</script></body></html> \ No newline at end of file diff --git a/src/index.jade b/src/index.jade index ad7053e..b961bc5 100644 --- a/src/index.jade +++ b/src/index.jade @@ -1,157 +1,157 @@ doctype html html(lang="en-GB") head meta(http-equiv="Content-Type", content="text/html; charset=utf-8") link(rel="shortcut icon", type="image/x-icon", href="favicon.ico") title #grid // Demo styles style(type="text/css") include ./partial/demo.css // Hashgrid styles style(type="text/css") include ./partial/hashgrid.css body main#content h1 | #grid&nbsp; em v10 p.summary em 30 Nov 2015 span : | #grid (or “Hashgrid”) is a little tool that inserts a&#160; a(href="http://en.wikipedia.org/wiki/Grid_(page_layout)") layout grid | &nbsp;in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit&nbsp; span(class="key") g | on your keyboard. h2 Download p#download a(href="https://github.com/dotjay/hashgrid/tags") Download #grid | &nbsp;from&nbsp; a(href="https://github.com/dotjay/hashgrid") GitHub h2#features Features ul li Adaptable for all layout widths and alignments li Adaptable for any vertical rhythm value li Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids li Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters p #grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids. h2#installation Installation ol li h3 Copy the&nbsp; a(href="https://github.com/dotjay/hashgrid/tree/main/dist/javascripts") hashgrid.js | &nbsp;script to your project li h3 Add this script to your page(s) just before the closing <code>&#60;/body&#62;</code> tag include ./partial/js_code.jade li h3 Add the CSS to your page(s) include ./partial/css_code.jade li h3 Modify #grid to suit your needs p The CSS and JavaScript is annotated to help you. h2#usage Usage p The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first. dl dt <span class="key">g</span> dd Show the grid until you release. dt <span class="key">g</span> + <span class="key">h</span> dd Show and hold the grid (<span class="key">g</span> will remove it again). dt <span class="key">g</span> + <span class="key">f</span> dd Toggle the grid to the foreground and back. Pressing <span class="key">f</span> while the grid is held also works. dt <span class="key">g</span> + <span class="key">j</span> dd Jump to the next grid. Pressing <span class="key">j</span> while the grid is held also works. p <em>Note: Hashgrid remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em> h2#release-notes Release Notes dl dt v10&#8201;&#8212;&#8201;30 Nov 2015 dd Works with vanilla JavaScript - jQuery is no longer required - thanks to <a href="https://github.com/widatama">widatama</a>. dt v9&#8201;&#8212;&#8201;30 May 2013 dd Minor release: Improved example usage to avoid conflicts. dt v8&#8201;&#8212;&#8201;6 Oct 2012 dd ul li Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="http://www.tomarnold.de/">Tom Arnold</a>. li Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="https://github.com/callumacrae">Callum Macrae</a>. li Fixes to cookie handling. Thanks to <a href="http://loonypandora.co.uk/">James Aitken</a>. li Optimisations. dt v7&#8201;&#8212;&#8201;11 Jun 2011 dd Minor release: Updated license references. dt v6&#8201;&#8212;&#8201;10 Jun 2011 - dd Minor release: Optimisations (thanks to <a href="http://andrewjaswa.com/">Andrew Jaswa</a> for contributions), and now released under an Apache License. + dd Minor release: Optimisations (thanks to <a href="https://github.com/ajaswa/">Andrew Jaswa</a> for contributions), and now released under an Apache License. dt v5&#8201;&#8212;&#8201;3 Nov 2010 dd ul li Vertical grid lines can now be set using CSS&#8230; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution. li Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property. li Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback. dt v4&#8201;&#8212;&#8201;29 Mar 2010 dd Fixes for multiple grid support under WebKit (Safari and Chrome). dt v3&#8201;&#8212;&#8201;22 Feb 2010 dd Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms. dt v2&#8201;&#8212;&#8201;2 Feb 2010 dd ul li Keys are now more easily configured (see top of hashgrid.js). li Fixed crash when using with disabled CSS. li Renamed the GridOverlay object to hashgrid. dt v1&#8201;&#8212;&#8201;21 Dec 2009 dd First release. h2#known-issues Known Issues ul li No known issues. h2#license License p Copyright 2013-2022 Jon Gibbins p Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br/> a(href="http://www.apache.org/licenses/LICENSE-2.0") http://www.apache.org/licenses/LICENSE-2.0 p <br/>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. p This essentially means that you&#8217;re free to copy, modify and distribute it for any project so long as you provide clear attribution to the author. <a href="https://dotjay.com/contact">Get in touch</a> if you need a different license. div#footer(role="contentinfo") p #grid was built by <a href="https://dotjay.com/">Jon Gibbins</a> and designed by <a href="https://jontangerine.com/">Jon Tan</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only. // Include the Hashgrid script script(type="text/javascript" src="dist/javascripts/hashgrid.js") // Kick Hashgrid into action script. var hg = new Hashgrid({ numberOfGrids: 2 });
dotjay/hashgrid
b14c6865ce3a0b54ba37b94aa2b2ba8f2ebe5643
Correct link to Callum Macrae
diff --git a/index.html b/index.html index 39029f0..9b07fa0 100644 --- a/index.html +++ b/index.html @@ -1,317 +1,317 @@ <!DOCTYPE html><html lang="en-GB"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><link rel="shortcut icon" type="image/x-icon" href="favicon.ico"><title>#grid</title> <!-- Demo styles--> <style type="text/css"> /* Putting inline rules here so the document can be downloaded with style */ body{ font-size: 1em; line-height: 1.25; font-family: Arial, sans-serif; background: White; color: DimGray; margin: 0; padding: 0 20px; } #content{ font-size: 16px; line-height: 20px; position: relative; } #content{ width: 620px; margin: 0 auto; } #footer{ border-top: 1px dotted DarkGray; padding-top: 19px; } h1, h2{ color: Black; font-weight: normal; } h1{ font-size: 36px; line-height: 40px; margin: 40px 0 20px; padding-bottom: 19px; border-bottom: 1px dotted DarkGray; } h1 em{ font-style: normal; color: DarkGray; font-size: 16px; line-height: 20px; margin: 0 0 20px; } h2, h3{ font-size: 16px; font-weight: 700; line-height: 20px; margin: 0 0 20px; } h3{ font-weight: 300; } a:link, a:visited{ color: Black; text-decoration: none; padding: 0 2px; background-color: WhiteSmoke; border-bottom: 1px solid Gold; } a:focus{ outline: none; } a:focus, a:hover, a:active{ background-color: Khaki; border-bottom: 1px solid GoldenRod; } p, ul{ padding: 0; margin: 0 0 20px; } dl, ol{ padding: 0; margin: 0; } ul{ list-style: circle; } ol li{ margin-bottom: 20px; } dd{ margin: 0 0 20px 0; } del{ text-decoration: line-through; opacity: 0.75; } ins{ text-decoration: none; } code{ font-size: 14px; line-height: 1; } textarea{ font-family: 'Courier New', monospace; font-size: 14px; line-height: 20px; display: block; width: 600px; margin: 0 0 20px; padding: 20px 0 0 15px; border: 0; color: Black; background: Gainsboro; border-left: 5px solid DarkGray; } #javascript-code{ height: 300px; } #css-code{ height: 1560px; } .summary em{ font-style: normal; position: absolute; color: DarkGray; right: 0; top: 18px; width: 140px; } .summary em span{ position: absolute; left: -9999px; } #download{ line-height: 60px; padding: 0 40px 0 15px; border-left: 5px solid DarkGray; background: Gainsboro; color: DimGray; } span.key{ color: Black; text-transform: uppercase; } </style> <!-- Hashgrid styles--> <style type="text/css"> /** * Hashgrid */ #grid{ /* * Spreads the whole page by default * Adjust to match your container */ /*width: 100%;*/ width: 980px; position: absolute; height: 100%; top: 0; left: 50%; margin-left: -490px; overflow: hidden; } .hashgrid-column-container { position: absolute; height: 100%; width: 100%; top: 0; left: 0; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ .hashgrid__column{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-left: 19px; height: 100%; float: left; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ .hashgrid__row{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option when instantiating Hashgrid. * e.g. * * var hg = new Hashgrid({ * numberOfGrids: 2 * }); */ #hashgrid.hashgrid2, #hashgrid.hashgrid2 .hashgrid-column-container{ /* Container width adjustments */ padding: 0 160px; width: 660px; } #hashgrid.hashgrid2 .hashgrid__column{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </style> </head><body><main id="content"><h1>#grid&nbsp;<em>v10</em></h1><p class="summary"><em>30 Nov 2015<span>:</span></em>#grid (or “Hashgrid”) is a little tool that inserts a&#160;<a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a>&nbsp;in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit&nbsp;<span class="key">g</span> on your keyboard.</p><h2>Download</h2><p id="download"><a href="https://github.com/dotjay/hashgrid/tags">Download #grid</a>&nbsp;from&nbsp;<a href="https://github.com/dotjay/hashgrid">GitHub</a></p><h2 id="features">Features</h2><ul><li>Adaptable for all layout widths and alignments</li><li>Adaptable for any vertical rhythm value</li><li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li><li>Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters</li></ul><p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p><h2 id="installation">Installation</h2><ol><li><h3>Copy the&nbsp;<a href="https://github.com/dotjay/hashgrid/tree/main/dist/javascripts">hashgrid.js</a>&nbsp;script to your project</h3></li><li><h3>Add this script to your page(s) just before the closing <code>&#60;/body&#62;</code> tag</h3><textarea id="javascript-code" cols="68" rows="15" readonly="readonly">&#60;!-- Include the hashgrid script --&#62; &#60;script type="text/javascript" src="hashgrid.js"&#62;&#60;/script&#62; &#60;!-- Kick hashgrid into action --&#62; &#60;script type="text/javascript"&#62; var grid = new Hashgrid({ numberOfGrids: 2 }); &#60;/script&#62; &#60;!-- Note: Use window onload if your css is not inlined --&#62; &#60;script type="text/javascript"&#62; window.addEventListener("load", function(event) { var grid = new Hashgrid({ numberOfGrids: 2 }); }); &#60;/script&#62;</textarea></li><li><h3>Add the CSS to your page(s)</h3><textarea id="css-code" cols="68" rows="64" readonly="readonly">/** * Grid */ #hashgrid{ /* * Spreads the whole page by default * Adjust to match your container */ /*width: 100%;*/ width: 980px; position: absolute; height: 100%; top: 0; left: 50%; margin-left: -490px; overflow: hidden; } .hashgrid-column-container { position: absolute; height: 100%; width: 100%; top: 0; left: 0; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ .hashgrid__column{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-left: 19px; height: 100%; float: left; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ .hashgrid__row{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option when instantiating hashgrid. * e.g. * * var hg = new Hashgrid({ * numberOfGrids: 2 * }); */ #hashgrid.hashgrid2, #hashgrid.hashgrid2 .hashgrid-column-container{ /* Container width adjustments */ padding: 0 160px; width: 660px; } #hashgrid.hashgrid2 .hashgrid__column{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } -</textarea></li><li><h3>Modify #grid to suit your needs</h3><p>The CSS and JavaScript is annotated to help you.</p></li></ol><h2 id="usage">Usage</h2><p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p><dl><dt><span class="key">g</span></dt><dd>Show the grid until you release.</dd><dt><span class="key">g</span> + <span class="key">h</span></dt><dd>Show and hold the grid (<span class="key">g</span> will remove it again).</dd><dt><span class="key">g</span> + <span class="key">f</span></dt><dd>Toggle the grid to the foreground and back. Pressing <span class="key">f</span> while the grid is held also works.</dd><dt><span class="key">g</span> + <span class="key">j</span></dt><dd>Jump to the next grid. Pressing <span class="key">j</span> while the grid is held also works.</dd></dl><p><em>Note: Hashgrid remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em></p><h2 id="release-notes">Release Notes</h2><dl><dt>v10&#8201;&#8212;&#8201;30 Nov 2015</dt><dd>Works with vanilla JavaScript - jQuery is no longer required - thanks to <a href="https://github.com/widatama">widatama</a>.</dd><dt>v9&#8201;&#8212;&#8201;30 May 2013</dt><dd>Minor release: Improved example usage to avoid conflicts.</dd><dt>v8&#8201;&#8212;&#8201;6 Oct 2012</dt><dd><ul><li>Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="http://www.tomarnold.de/">Tom Arnold</a>.</li><li>Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="http://lynx.io/">Callum Macrae</a>.</li><li>Fixes to cookie handling. Thanks to <a href="http://loonypandora.co.uk/">James Aitken</a>.</li><li>Optimisations.</li></ul></dd><dt>v7&#8201;&#8212;&#8201;11 Jun 2011</dt><dd>Minor release: Updated license references.</dd><dt>v6&#8201;&#8212;&#8201;10 Jun 2011</dt><dd>Minor release: Optimisations (thanks to <a href="http://andrewjaswa.com/">Andrew Jaswa</a> for contributions), and now released under an Apache License.</dd><dt>v5&#8201;&#8212;&#8201;3 Nov 2010</dt><dd><ul><li>Vertical grid lines can now be set using CSS&#8230; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution.</li><li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li><li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback.</li></ul></dd><dt>v4&#8201;&#8212;&#8201;29 Mar 2010</dt><dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd><dt>v3&#8201;&#8212;&#8201;22 Feb 2010</dt><dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd><dt>v2&#8201;&#8212;&#8201;2 Feb 2010</dt><dd><ul><li>Keys are now more easily configured (see top of hashgrid.js).</li><li>Fixed crash when using with disabled CSS.</li><li>Renamed the GridOverlay object to hashgrid.</li></ul></dd><dt>v1&#8201;&#8212;&#8201;21 Dec 2009</dt><dd>First release.</dd></dl><h2 id="known-issues">Known Issues</h2><ul><li>No known issues.</li></ul><h2 id="license">License</h2><p>Copyright 2013-2022 Jon Gibbins</p><p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br/></p><a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a><p><br/>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.</p><p>This essentially means that you&#8217;re free to copy, modify and distribute it for any project so long as you provide clear attribution to the author. <a href="https://dotjay.com/contact">Get in touch</a> if you need a different license.</p><div id="footer" role="contentinfo"><p>#grid was built by <a href="https://dotjay.com/">Jon Gibbins</a> and designed by <a href="https://jontangerine.com/">Jon Tan</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p></div></main><!-- Include the hashgrid script--><script type="text/javascript" src="dist/javascripts/hashgrid.js"></script><!-- Kick hashgrid into action--><script>var hg = new Hashgrid({ +</textarea></li><li><h3>Modify #grid to suit your needs</h3><p>The CSS and JavaScript is annotated to help you.</p></li></ol><h2 id="usage">Usage</h2><p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p><dl><dt><span class="key">g</span></dt><dd>Show the grid until you release.</dd><dt><span class="key">g</span> + <span class="key">h</span></dt><dd>Show and hold the grid (<span class="key">g</span> will remove it again).</dd><dt><span class="key">g</span> + <span class="key">f</span></dt><dd>Toggle the grid to the foreground and back. Pressing <span class="key">f</span> while the grid is held also works.</dd><dt><span class="key">g</span> + <span class="key">j</span></dt><dd>Jump to the next grid. Pressing <span class="key">j</span> while the grid is held also works.</dd></dl><p><em>Note: Hashgrid remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em></p><h2 id="release-notes">Release Notes</h2><dl><dt>v10&#8201;&#8212;&#8201;30 Nov 2015</dt><dd>Works with vanilla JavaScript - jQuery is no longer required - thanks to <a href="https://github.com/widatama">widatama</a>.</dd><dt>v9&#8201;&#8212;&#8201;30 May 2013</dt><dd>Minor release: Improved example usage to avoid conflicts.</dd><dt>v8&#8201;&#8212;&#8201;6 Oct 2012</dt><dd><ul><li>Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="http://www.tomarnold.de/">Tom Arnold</a>.</li><li>Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="https://github.com/callumacrae">Callum Macrae</a>.</li><li>Fixes to cookie handling. Thanks to <a href="http://loonypandora.co.uk/">James Aitken</a>.</li><li>Optimisations.</li></ul></dd><dt>v7&#8201;&#8212;&#8201;11 Jun 2011</dt><dd>Minor release: Updated license references.</dd><dt>v6&#8201;&#8212;&#8201;10 Jun 2011</dt><dd>Minor release: Optimisations (thanks to <a href="http://andrewjaswa.com/">Andrew Jaswa</a> for contributions), and now released under an Apache License.</dd><dt>v5&#8201;&#8212;&#8201;3 Nov 2010</dt><dd><ul><li>Vertical grid lines can now be set using CSS&#8230; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution.</li><li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li><li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback.</li></ul></dd><dt>v4&#8201;&#8212;&#8201;29 Mar 2010</dt><dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd><dt>v3&#8201;&#8212;&#8201;22 Feb 2010</dt><dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd><dt>v2&#8201;&#8212;&#8201;2 Feb 2010</dt><dd><ul><li>Keys are now more easily configured (see top of hashgrid.js).</li><li>Fixed crash when using with disabled CSS.</li><li>Renamed the GridOverlay object to hashgrid.</li></ul></dd><dt>v1&#8201;&#8212;&#8201;21 Dec 2009</dt><dd>First release.</dd></dl><h2 id="known-issues">Known Issues</h2><ul><li>No known issues.</li></ul><h2 id="license">License</h2><p>Copyright 2013-2022 Jon Gibbins</p><p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br/></p><a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a><p><br/>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.</p><p>This essentially means that you&#8217;re free to copy, modify and distribute it for any project so long as you provide clear attribution to the author. <a href="https://dotjay.com/contact">Get in touch</a> if you need a different license.</p><div id="footer" role="contentinfo"><p>#grid was built by <a href="https://dotjay.com/">Jon Gibbins</a> and designed by <a href="https://jontangerine.com/">Jon Tan</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p></div></main><!-- Include the hashgrid script--><script type="text/javascript" src="dist/javascripts/hashgrid.js"></script><!-- Kick hashgrid into action--><script>var hg = new Hashgrid({ numberOfGrids: 2 });</script></body></html> \ No newline at end of file diff --git a/src/index.jade b/src/index.jade index 9c399ef..ad7053e 100644 --- a/src/index.jade +++ b/src/index.jade @@ -1,157 +1,157 @@ doctype html html(lang="en-GB") head meta(http-equiv="Content-Type", content="text/html; charset=utf-8") link(rel="shortcut icon", type="image/x-icon", href="favicon.ico") title #grid // Demo styles style(type="text/css") include ./partial/demo.css // Hashgrid styles style(type="text/css") include ./partial/hashgrid.css body main#content h1 | #grid&nbsp; em v10 p.summary em 30 Nov 2015 span : | #grid (or “Hashgrid”) is a little tool that inserts a&#160; a(href="http://en.wikipedia.org/wiki/Grid_(page_layout)") layout grid | &nbsp;in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit&nbsp; span(class="key") g | on your keyboard. h2 Download p#download a(href="https://github.com/dotjay/hashgrid/tags") Download #grid | &nbsp;from&nbsp; a(href="https://github.com/dotjay/hashgrid") GitHub h2#features Features ul li Adaptable for all layout widths and alignments li Adaptable for any vertical rhythm value li Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids li Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters p #grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids. h2#installation Installation ol li h3 Copy the&nbsp; a(href="https://github.com/dotjay/hashgrid/tree/main/dist/javascripts") hashgrid.js | &nbsp;script to your project li h3 Add this script to your page(s) just before the closing <code>&#60;/body&#62;</code> tag include ./partial/js_code.jade li h3 Add the CSS to your page(s) include ./partial/css_code.jade li h3 Modify #grid to suit your needs p The CSS and JavaScript is annotated to help you. h2#usage Usage p The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first. dl dt <span class="key">g</span> dd Show the grid until you release. dt <span class="key">g</span> + <span class="key">h</span> dd Show and hold the grid (<span class="key">g</span> will remove it again). dt <span class="key">g</span> + <span class="key">f</span> dd Toggle the grid to the foreground and back. Pressing <span class="key">f</span> while the grid is held also works. dt <span class="key">g</span> + <span class="key">j</span> dd Jump to the next grid. Pressing <span class="key">j</span> while the grid is held also works. p <em>Note: Hashgrid remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em> h2#release-notes Release Notes dl dt v10&#8201;&#8212;&#8201;30 Nov 2015 dd Works with vanilla JavaScript - jQuery is no longer required - thanks to <a href="https://github.com/widatama">widatama</a>. dt v9&#8201;&#8212;&#8201;30 May 2013 dd Minor release: Improved example usage to avoid conflicts. dt v8&#8201;&#8212;&#8201;6 Oct 2012 dd ul li Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="http://www.tomarnold.de/">Tom Arnold</a>. - li Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="http://lynx.io/">Callum Macrae</a>. + li Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="https://github.com/callumacrae">Callum Macrae</a>. li Fixes to cookie handling. Thanks to <a href="http://loonypandora.co.uk/">James Aitken</a>. li Optimisations. dt v7&#8201;&#8212;&#8201;11 Jun 2011 dd Minor release: Updated license references. dt v6&#8201;&#8212;&#8201;10 Jun 2011 dd Minor release: Optimisations (thanks to <a href="http://andrewjaswa.com/">Andrew Jaswa</a> for contributions), and now released under an Apache License. dt v5&#8201;&#8212;&#8201;3 Nov 2010 dd ul li Vertical grid lines can now be set using CSS&#8230; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution. li Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property. li Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback. dt v4&#8201;&#8212;&#8201;29 Mar 2010 dd Fixes for multiple grid support under WebKit (Safari and Chrome). dt v3&#8201;&#8212;&#8201;22 Feb 2010 dd Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms. dt v2&#8201;&#8212;&#8201;2 Feb 2010 dd ul li Keys are now more easily configured (see top of hashgrid.js). li Fixed crash when using with disabled CSS. li Renamed the GridOverlay object to hashgrid. dt v1&#8201;&#8212;&#8201;21 Dec 2009 dd First release. h2#known-issues Known Issues ul li No known issues. h2#license License p Copyright 2013-2022 Jon Gibbins p Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br/> a(href="http://www.apache.org/licenses/LICENSE-2.0") http://www.apache.org/licenses/LICENSE-2.0 p <br/>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. p This essentially means that you&#8217;re free to copy, modify and distribute it for any project so long as you provide clear attribution to the author. <a href="https://dotjay.com/contact">Get in touch</a> if you need a different license. div#footer(role="contentinfo") p #grid was built by <a href="https://dotjay.com/">Jon Gibbins</a> and designed by <a href="https://jontangerine.com/">Jon Tan</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only. // Include the Hashgrid script script(type="text/javascript" src="dist/javascripts/hashgrid.js") // Kick Hashgrid into action script. var hg = new Hashgrid({ numberOfGrids: 2 });
dotjay/hashgrid
14ea49c9c797a560949a87c4bcaf7c4a104013a5
Correct link to latest hashgrid.js
diff --git a/index.html b/index.html index 884146f..39029f0 100644 --- a/index.html +++ b/index.html @@ -1,317 +1,317 @@ <!DOCTYPE html><html lang="en-GB"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><link rel="shortcut icon" type="image/x-icon" href="favicon.ico"><title>#grid</title> <!-- Demo styles--> <style type="text/css"> /* Putting inline rules here so the document can be downloaded with style */ body{ font-size: 1em; line-height: 1.25; font-family: Arial, sans-serif; background: White; color: DimGray; margin: 0; padding: 0 20px; } #content{ font-size: 16px; line-height: 20px; position: relative; } #content{ width: 620px; margin: 0 auto; } #footer{ border-top: 1px dotted DarkGray; padding-top: 19px; } h1, h2{ color: Black; font-weight: normal; } h1{ font-size: 36px; line-height: 40px; margin: 40px 0 20px; padding-bottom: 19px; border-bottom: 1px dotted DarkGray; } h1 em{ font-style: normal; color: DarkGray; font-size: 16px; line-height: 20px; margin: 0 0 20px; } h2, h3{ font-size: 16px; font-weight: 700; line-height: 20px; margin: 0 0 20px; } h3{ font-weight: 300; } a:link, a:visited{ color: Black; text-decoration: none; padding: 0 2px; background-color: WhiteSmoke; border-bottom: 1px solid Gold; } a:focus{ outline: none; } a:focus, a:hover, a:active{ background-color: Khaki; border-bottom: 1px solid GoldenRod; } p, ul{ padding: 0; margin: 0 0 20px; } dl, ol{ padding: 0; margin: 0; } ul{ list-style: circle; } ol li{ margin-bottom: 20px; } dd{ margin: 0 0 20px 0; } del{ text-decoration: line-through; opacity: 0.75; } ins{ text-decoration: none; } code{ font-size: 14px; line-height: 1; } textarea{ font-family: 'Courier New', monospace; font-size: 14px; line-height: 20px; display: block; width: 600px; margin: 0 0 20px; padding: 20px 0 0 15px; border: 0; color: Black; background: Gainsboro; border-left: 5px solid DarkGray; } #javascript-code{ height: 300px; } #css-code{ height: 1560px; } .summary em{ font-style: normal; position: absolute; color: DarkGray; right: 0; top: 18px; width: 140px; } .summary em span{ position: absolute; left: -9999px; } #download{ line-height: 60px; padding: 0 40px 0 15px; border-left: 5px solid DarkGray; background: Gainsboro; color: DimGray; } span.key{ color: Black; text-transform: uppercase; } </style> <!-- Hashgrid styles--> <style type="text/css"> /** * Hashgrid */ -#hashgrid{ +#grid{ /* * Spreads the whole page by default * Adjust to match your container */ /*width: 100%;*/ width: 980px; position: absolute; height: 100%; top: 0; left: 50%; margin-left: -490px; overflow: hidden; } .hashgrid-column-container { position: absolute; height: 100%; width: 100%; top: 0; left: 0; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ .hashgrid__column{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-left: 19px; height: 100%; float: left; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ .hashgrid__row{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option when instantiating Hashgrid. * e.g. * * var hg = new Hashgrid({ * numberOfGrids: 2 * }); */ #hashgrid.hashgrid2, #hashgrid.hashgrid2 .hashgrid-column-container{ /* Container width adjustments */ padding: 0 160px; width: 660px; } #hashgrid.hashgrid2 .hashgrid__column{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </style> -</head><body><main id="content"><h1>#grid&nbsp;<em>v10</em></h1><p class="summary"><em>30 Nov 2015<span>:</span></em>#grid (or “Hashgrid”) is a little tool that inserts a&#160;<a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a>&nbsp;in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit&nbsp;<span class="key">g</span> on your keyboard.</p><h2>Download</h2><p id="download"><a href="https://github.com/dotjay/hashgrid/tags">Download #grid</a>&nbsp;from&nbsp;<a href="https://github.com/dotjay/hashgrid">GitHub</a></p><h2 id="features">Features</h2><ul><li>Adaptable for all layout widths and alignments</li><li>Adaptable for any vertical rhythm value</li><li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li><li>Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters</li></ul><p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p><h2 id="installation">Installation</h2><ol><li><h3>Copy the&nbsp;<a href="https://github.com/dotjay/hashgrid/blob/v9/hashgrid.js">hashgrid.js</a>&nbsp;script to your project</h3></li><li><h3>Add this script to your page(s) just before the closing <code>&#60;/body&#62;</code> tag</h3><textarea id="javascript-code" cols="68" rows="15" readonly="readonly">&#60;!-- Include the hashgrid script --&#62; +</head><body><main id="content"><h1>#grid&nbsp;<em>v10</em></h1><p class="summary"><em>30 Nov 2015<span>:</span></em>#grid (or “Hashgrid”) is a little tool that inserts a&#160;<a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a>&nbsp;in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit&nbsp;<span class="key">g</span> on your keyboard.</p><h2>Download</h2><p id="download"><a href="https://github.com/dotjay/hashgrid/tags">Download #grid</a>&nbsp;from&nbsp;<a href="https://github.com/dotjay/hashgrid">GitHub</a></p><h2 id="features">Features</h2><ul><li>Adaptable for all layout widths and alignments</li><li>Adaptable for any vertical rhythm value</li><li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li><li>Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters</li></ul><p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p><h2 id="installation">Installation</h2><ol><li><h3>Copy the&nbsp;<a href="https://github.com/dotjay/hashgrid/tree/main/dist/javascripts">hashgrid.js</a>&nbsp;script to your project</h3></li><li><h3>Add this script to your page(s) just before the closing <code>&#60;/body&#62;</code> tag</h3><textarea id="javascript-code" cols="68" rows="15" readonly="readonly">&#60;!-- Include the hashgrid script --&#62; &#60;script type="text/javascript" src="hashgrid.js"&#62;&#60;/script&#62; &#60;!-- Kick hashgrid into action --&#62; &#60;script type="text/javascript"&#62; var grid = new Hashgrid({ numberOfGrids: 2 }); &#60;/script&#62; &#60;!-- Note: Use window onload if your css is not inlined --&#62; &#60;script type="text/javascript"&#62; window.addEventListener("load", function(event) { var grid = new Hashgrid({ numberOfGrids: 2 }); }); &#60;/script&#62;</textarea></li><li><h3>Add the CSS to your page(s)</h3><textarea id="css-code" cols="68" rows="64" readonly="readonly">/** * Grid */ #hashgrid{ /* * Spreads the whole page by default * Adjust to match your container */ /*width: 100%;*/ width: 980px; position: absolute; height: 100%; top: 0; left: 50%; margin-left: -490px; overflow: hidden; } .hashgrid-column-container { position: absolute; height: 100%; width: 100%; top: 0; left: 0; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ .hashgrid__column{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-left: 19px; height: 100%; float: left; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ .hashgrid__row{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option when instantiating hashgrid. * e.g. * * var hg = new Hashgrid({ * numberOfGrids: 2 * }); */ #hashgrid.hashgrid2, #hashgrid.hashgrid2 .hashgrid-column-container{ /* Container width adjustments */ padding: 0 160px; width: 660px; } #hashgrid.hashgrid2 .hashgrid__column{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </textarea></li><li><h3>Modify #grid to suit your needs</h3><p>The CSS and JavaScript is annotated to help you.</p></li></ol><h2 id="usage">Usage</h2><p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p><dl><dt><span class="key">g</span></dt><dd>Show the grid until you release.</dd><dt><span class="key">g</span> + <span class="key">h</span></dt><dd>Show and hold the grid (<span class="key">g</span> will remove it again).</dd><dt><span class="key">g</span> + <span class="key">f</span></dt><dd>Toggle the grid to the foreground and back. Pressing <span class="key">f</span> while the grid is held also works.</dd><dt><span class="key">g</span> + <span class="key">j</span></dt><dd>Jump to the next grid. Pressing <span class="key">j</span> while the grid is held also works.</dd></dl><p><em>Note: Hashgrid remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em></p><h2 id="release-notes">Release Notes</h2><dl><dt>v10&#8201;&#8212;&#8201;30 Nov 2015</dt><dd>Works with vanilla JavaScript - jQuery is no longer required - thanks to <a href="https://github.com/widatama">widatama</a>.</dd><dt>v9&#8201;&#8212;&#8201;30 May 2013</dt><dd>Minor release: Improved example usage to avoid conflicts.</dd><dt>v8&#8201;&#8212;&#8201;6 Oct 2012</dt><dd><ul><li>Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="http://www.tomarnold.de/">Tom Arnold</a>.</li><li>Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="http://lynx.io/">Callum Macrae</a>.</li><li>Fixes to cookie handling. Thanks to <a href="http://loonypandora.co.uk/">James Aitken</a>.</li><li>Optimisations.</li></ul></dd><dt>v7&#8201;&#8212;&#8201;11 Jun 2011</dt><dd>Minor release: Updated license references.</dd><dt>v6&#8201;&#8212;&#8201;10 Jun 2011</dt><dd>Minor release: Optimisations (thanks to <a href="http://andrewjaswa.com/">Andrew Jaswa</a> for contributions), and now released under an Apache License.</dd><dt>v5&#8201;&#8212;&#8201;3 Nov 2010</dt><dd><ul><li>Vertical grid lines can now be set using CSS&#8230; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution.</li><li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li><li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback.</li></ul></dd><dt>v4&#8201;&#8212;&#8201;29 Mar 2010</dt><dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd><dt>v3&#8201;&#8212;&#8201;22 Feb 2010</dt><dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd><dt>v2&#8201;&#8212;&#8201;2 Feb 2010</dt><dd><ul><li>Keys are now more easily configured (see top of hashgrid.js).</li><li>Fixed crash when using with disabled CSS.</li><li>Renamed the GridOverlay object to hashgrid.</li></ul></dd><dt>v1&#8201;&#8212;&#8201;21 Dec 2009</dt><dd>First release.</dd></dl><h2 id="known-issues">Known Issues</h2><ul><li>No known issues.</li></ul><h2 id="license">License</h2><p>Copyright 2013-2022 Jon Gibbins</p><p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br/></p><a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a><p><br/>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.</p><p>This essentially means that you&#8217;re free to copy, modify and distribute it for any project so long as you provide clear attribution to the author. <a href="https://dotjay.com/contact">Get in touch</a> if you need a different license.</p><div id="footer" role="contentinfo"><p>#grid was built by <a href="https://dotjay.com/">Jon Gibbins</a> and designed by <a href="https://jontangerine.com/">Jon Tan</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p></div></main><!-- Include the hashgrid script--><script type="text/javascript" src="dist/javascripts/hashgrid.js"></script><!-- Kick hashgrid into action--><script>var hg = new Hashgrid({ numberOfGrids: 2 });</script></body></html> \ No newline at end of file diff --git a/src/index.jade b/src/index.jade index 55d5560..9c399ef 100644 --- a/src/index.jade +++ b/src/index.jade @@ -1,157 +1,157 @@ doctype html html(lang="en-GB") head meta(http-equiv="Content-Type", content="text/html; charset=utf-8") link(rel="shortcut icon", type="image/x-icon", href="favicon.ico") title #grid // Demo styles style(type="text/css") include ./partial/demo.css // Hashgrid styles style(type="text/css") include ./partial/hashgrid.css body main#content h1 | #grid&nbsp; em v10 p.summary em 30 Nov 2015 span : | #grid (or “Hashgrid”) is a little tool that inserts a&#160; a(href="http://en.wikipedia.org/wiki/Grid_(page_layout)") layout grid | &nbsp;in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit&nbsp; span(class="key") g | on your keyboard. h2 Download p#download a(href="https://github.com/dotjay/hashgrid/tags") Download #grid | &nbsp;from&nbsp; a(href="https://github.com/dotjay/hashgrid") GitHub h2#features Features ul li Adaptable for all layout widths and alignments li Adaptable for any vertical rhythm value li Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids li Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters p #grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids. h2#installation Installation ol li h3 Copy the&nbsp; - a(href="https://github.com/dotjay/hashgrid/blob/v10/hashgrid.js") hashgrid.js + a(href="https://github.com/dotjay/hashgrid/tree/main/dist/javascripts") hashgrid.js | &nbsp;script to your project li h3 Add this script to your page(s) just before the closing <code>&#60;/body&#62;</code> tag include ./partial/js_code.jade li h3 Add the CSS to your page(s) include ./partial/css_code.jade li h3 Modify #grid to suit your needs p The CSS and JavaScript is annotated to help you. h2#usage Usage p The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first. dl dt <span class="key">g</span> dd Show the grid until you release. dt <span class="key">g</span> + <span class="key">h</span> dd Show and hold the grid (<span class="key">g</span> will remove it again). dt <span class="key">g</span> + <span class="key">f</span> dd Toggle the grid to the foreground and back. Pressing <span class="key">f</span> while the grid is held also works. dt <span class="key">g</span> + <span class="key">j</span> dd Jump to the next grid. Pressing <span class="key">j</span> while the grid is held also works. p <em>Note: Hashgrid remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em> h2#release-notes Release Notes dl dt v10&#8201;&#8212;&#8201;30 Nov 2015 dd Works with vanilla JavaScript - jQuery is no longer required - thanks to <a href="https://github.com/widatama">widatama</a>. dt v9&#8201;&#8212;&#8201;30 May 2013 dd Minor release: Improved example usage to avoid conflicts. dt v8&#8201;&#8212;&#8201;6 Oct 2012 dd ul li Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="http://www.tomarnold.de/">Tom Arnold</a>. li Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="http://lynx.io/">Callum Macrae</a>. li Fixes to cookie handling. Thanks to <a href="http://loonypandora.co.uk/">James Aitken</a>. li Optimisations. dt v7&#8201;&#8212;&#8201;11 Jun 2011 dd Minor release: Updated license references. dt v6&#8201;&#8212;&#8201;10 Jun 2011 dd Minor release: Optimisations (thanks to <a href="http://andrewjaswa.com/">Andrew Jaswa</a> for contributions), and now released under an Apache License. dt v5&#8201;&#8212;&#8201;3 Nov 2010 dd ul li Vertical grid lines can now be set using CSS&#8230; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution. li Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property. li Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback. dt v4&#8201;&#8212;&#8201;29 Mar 2010 dd Fixes for multiple grid support under WebKit (Safari and Chrome). dt v3&#8201;&#8212;&#8201;22 Feb 2010 dd Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms. dt v2&#8201;&#8212;&#8201;2 Feb 2010 dd ul li Keys are now more easily configured (see top of hashgrid.js). li Fixed crash when using with disabled CSS. li Renamed the GridOverlay object to hashgrid. dt v1&#8201;&#8212;&#8201;21 Dec 2009 dd First release. h2#known-issues Known Issues ul li No known issues. h2#license License p Copyright 2013-2022 Jon Gibbins p Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br/> a(href="http://www.apache.org/licenses/LICENSE-2.0") http://www.apache.org/licenses/LICENSE-2.0 p <br/>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. p This essentially means that you&#8217;re free to copy, modify and distribute it for any project so long as you provide clear attribution to the author. <a href="https://dotjay.com/contact">Get in touch</a> if you need a different license. div#footer(role="contentinfo") p #grid was built by <a href="https://dotjay.com/">Jon Gibbins</a> and designed by <a href="https://jontangerine.com/">Jon Tan</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only. // Include the Hashgrid script script(type="text/javascript" src="dist/javascripts/hashgrid.js") // Kick Hashgrid into action script. var hg = new Hashgrid({ numberOfGrids: 2 });
dotjay/hashgrid
d4138c9f61fcb05390321743a3e42017102c6ce1
Correct download link
diff --git a/index.html b/index.html index ab4a563..884146f 100644 --- a/index.html +++ b/index.html @@ -1,317 +1,317 @@ <!DOCTYPE html><html lang="en-GB"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><link rel="shortcut icon" type="image/x-icon" href="favicon.ico"><title>#grid</title> <!-- Demo styles--> <style type="text/css"> /* Putting inline rules here so the document can be downloaded with style */ body{ font-size: 1em; line-height: 1.25; font-family: Arial, sans-serif; background: White; color: DimGray; margin: 0; padding: 0 20px; } #content{ font-size: 16px; line-height: 20px; position: relative; } #content{ width: 620px; margin: 0 auto; } #footer{ border-top: 1px dotted DarkGray; padding-top: 19px; } h1, h2{ color: Black; font-weight: normal; } h1{ font-size: 36px; line-height: 40px; margin: 40px 0 20px; padding-bottom: 19px; border-bottom: 1px dotted DarkGray; } h1 em{ font-style: normal; color: DarkGray; font-size: 16px; line-height: 20px; margin: 0 0 20px; } h2, h3{ font-size: 16px; font-weight: 700; line-height: 20px; margin: 0 0 20px; } h3{ font-weight: 300; } a:link, a:visited{ color: Black; text-decoration: none; padding: 0 2px; background-color: WhiteSmoke; border-bottom: 1px solid Gold; } a:focus{ outline: none; } a:focus, a:hover, a:active{ background-color: Khaki; border-bottom: 1px solid GoldenRod; } p, ul{ padding: 0; margin: 0 0 20px; } dl, ol{ padding: 0; margin: 0; } ul{ list-style: circle; } ol li{ margin-bottom: 20px; } dd{ margin: 0 0 20px 0; } del{ text-decoration: line-through; opacity: 0.75; } ins{ text-decoration: none; } code{ font-size: 14px; line-height: 1; } textarea{ font-family: 'Courier New', monospace; font-size: 14px; line-height: 20px; display: block; width: 600px; margin: 0 0 20px; padding: 20px 0 0 15px; border: 0; color: Black; background: Gainsboro; border-left: 5px solid DarkGray; } #javascript-code{ height: 300px; } #css-code{ height: 1560px; } .summary em{ font-style: normal; position: absolute; color: DarkGray; right: 0; top: 18px; width: 140px; } .summary em span{ position: absolute; left: -9999px; } #download{ line-height: 60px; padding: 0 40px 0 15px; border-left: 5px solid DarkGray; background: Gainsboro; color: DimGray; } span.key{ color: Black; text-transform: uppercase; } </style> <!-- Hashgrid styles--> <style type="text/css"> /** * Hashgrid */ #hashgrid{ /* * Spreads the whole page by default * Adjust to match your container */ /*width: 100%;*/ width: 980px; position: absolute; height: 100%; top: 0; left: 50%; margin-left: -490px; overflow: hidden; } .hashgrid-column-container { position: absolute; height: 100%; width: 100%; top: 0; left: 0; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ .hashgrid__column{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-left: 19px; height: 100%; float: left; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ .hashgrid__row{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option when instantiating Hashgrid. * e.g. * * var hg = new Hashgrid({ * numberOfGrids: 2 * }); */ #hashgrid.hashgrid2, #hashgrid.hashgrid2 .hashgrid-column-container{ /* Container width adjustments */ padding: 0 160px; width: 660px; } #hashgrid.hashgrid2 .hashgrid__column{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </style> -</head><body><main id="content"><h1>#grid&nbsp;<em>v10</em></h1><p class="summary"><em>30 Nov 2015<span>:</span></em>#grid (or “Hashgrid”) is a little tool that inserts a&#160;<a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a>&nbsp;in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit&nbsp;<span class="key">g</span> on your keyboard.</p><h2>Download</h2><p id="download"><a href="https://github.com/dotjay/hashgrid/downloads">Download #grid</a>&nbsp;from&nbsp;<a href="https://github.com/dotjay/hashgrid">GitHub</a></p><h2 id="features">Features</h2><ul><li>Adaptable for all layout widths and alignments</li><li>Adaptable for any vertical rhythm value</li><li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li><li>Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters</li></ul><p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p><h2 id="installation">Installation</h2><ol><li><h3>Copy the&nbsp;<a href="https://github.com/dotjay/hashgrid/blob/v9/hashgrid.js">hashgrid.js</a>&nbsp;script to your project</h3></li><li><h3>Add this script to your page(s) just before the closing <code>&#60;/body&#62;</code> tag</h3><textarea id="javascript-code" cols="68" rows="15" readonly="readonly">&#60;!-- Include the hashgrid script --&#62; +</head><body><main id="content"><h1>#grid&nbsp;<em>v10</em></h1><p class="summary"><em>30 Nov 2015<span>:</span></em>#grid (or “Hashgrid”) is a little tool that inserts a&#160;<a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a>&nbsp;in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit&nbsp;<span class="key">g</span> on your keyboard.</p><h2>Download</h2><p id="download"><a href="https://github.com/dotjay/hashgrid/tags">Download #grid</a>&nbsp;from&nbsp;<a href="https://github.com/dotjay/hashgrid">GitHub</a></p><h2 id="features">Features</h2><ul><li>Adaptable for all layout widths and alignments</li><li>Adaptable for any vertical rhythm value</li><li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li><li>Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters</li></ul><p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p><h2 id="installation">Installation</h2><ol><li><h3>Copy the&nbsp;<a href="https://github.com/dotjay/hashgrid/blob/v9/hashgrid.js">hashgrid.js</a>&nbsp;script to your project</h3></li><li><h3>Add this script to your page(s) just before the closing <code>&#60;/body&#62;</code> tag</h3><textarea id="javascript-code" cols="68" rows="15" readonly="readonly">&#60;!-- Include the hashgrid script --&#62; &#60;script type="text/javascript" src="hashgrid.js"&#62;&#60;/script&#62; &#60;!-- Kick hashgrid into action --&#62; &#60;script type="text/javascript"&#62; var grid = new Hashgrid({ numberOfGrids: 2 }); &#60;/script&#62; &#60;!-- Note: Use window onload if your css is not inlined --&#62; &#60;script type="text/javascript"&#62; window.addEventListener("load", function(event) { var grid = new Hashgrid({ numberOfGrids: 2 }); }); &#60;/script&#62;</textarea></li><li><h3>Add the CSS to your page(s)</h3><textarea id="css-code" cols="68" rows="64" readonly="readonly">/** * Grid */ #hashgrid{ /* * Spreads the whole page by default * Adjust to match your container */ /*width: 100%;*/ width: 980px; position: absolute; height: 100%; top: 0; left: 50%; margin-left: -490px; overflow: hidden; } .hashgrid-column-container { position: absolute; height: 100%; width: 100%; top: 0; left: 0; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ .hashgrid__column{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-left: 19px; height: 100%; float: left; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ .hashgrid__row{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option when instantiating hashgrid. * e.g. * * var hg = new Hashgrid({ * numberOfGrids: 2 * }); */ #hashgrid.hashgrid2, #hashgrid.hashgrid2 .hashgrid-column-container{ /* Container width adjustments */ padding: 0 160px; width: 660px; } #hashgrid.hashgrid2 .hashgrid__column{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </textarea></li><li><h3>Modify #grid to suit your needs</h3><p>The CSS and JavaScript is annotated to help you.</p></li></ol><h2 id="usage">Usage</h2><p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p><dl><dt><span class="key">g</span></dt><dd>Show the grid until you release.</dd><dt><span class="key">g</span> + <span class="key">h</span></dt><dd>Show and hold the grid (<span class="key">g</span> will remove it again).</dd><dt><span class="key">g</span> + <span class="key">f</span></dt><dd>Toggle the grid to the foreground and back. Pressing <span class="key">f</span> while the grid is held also works.</dd><dt><span class="key">g</span> + <span class="key">j</span></dt><dd>Jump to the next grid. Pressing <span class="key">j</span> while the grid is held also works.</dd></dl><p><em>Note: Hashgrid remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em></p><h2 id="release-notes">Release Notes</h2><dl><dt>v10&#8201;&#8212;&#8201;30 Nov 2015</dt><dd>Works with vanilla JavaScript - jQuery is no longer required - thanks to <a href="https://github.com/widatama">widatama</a>.</dd><dt>v9&#8201;&#8212;&#8201;30 May 2013</dt><dd>Minor release: Improved example usage to avoid conflicts.</dd><dt>v8&#8201;&#8212;&#8201;6 Oct 2012</dt><dd><ul><li>Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="http://www.tomarnold.de/">Tom Arnold</a>.</li><li>Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="http://lynx.io/">Callum Macrae</a>.</li><li>Fixes to cookie handling. Thanks to <a href="http://loonypandora.co.uk/">James Aitken</a>.</li><li>Optimisations.</li></ul></dd><dt>v7&#8201;&#8212;&#8201;11 Jun 2011</dt><dd>Minor release: Updated license references.</dd><dt>v6&#8201;&#8212;&#8201;10 Jun 2011</dt><dd>Minor release: Optimisations (thanks to <a href="http://andrewjaswa.com/">Andrew Jaswa</a> for contributions), and now released under an Apache License.</dd><dt>v5&#8201;&#8212;&#8201;3 Nov 2010</dt><dd><ul><li>Vertical grid lines can now be set using CSS&#8230; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution.</li><li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li><li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback.</li></ul></dd><dt>v4&#8201;&#8212;&#8201;29 Mar 2010</dt><dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd><dt>v3&#8201;&#8212;&#8201;22 Feb 2010</dt><dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd><dt>v2&#8201;&#8212;&#8201;2 Feb 2010</dt><dd><ul><li>Keys are now more easily configured (see top of hashgrid.js).</li><li>Fixed crash when using with disabled CSS.</li><li>Renamed the GridOverlay object to hashgrid.</li></ul></dd><dt>v1&#8201;&#8212;&#8201;21 Dec 2009</dt><dd>First release.</dd></dl><h2 id="known-issues">Known Issues</h2><ul><li>No known issues.</li></ul><h2 id="license">License</h2><p>Copyright 2013-2022 Jon Gibbins</p><p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br/></p><a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a><p><br/>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.</p><p>This essentially means that you&#8217;re free to copy, modify and distribute it for any project so long as you provide clear attribution to the author. <a href="https://dotjay.com/contact">Get in touch</a> if you need a different license.</p><div id="footer" role="contentinfo"><p>#grid was built by <a href="https://dotjay.com/">Jon Gibbins</a> and designed by <a href="https://jontangerine.com/">Jon Tan</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p></div></main><!-- Include the hashgrid script--><script type="text/javascript" src="dist/javascripts/hashgrid.js"></script><!-- Kick hashgrid into action--><script>var hg = new Hashgrid({ numberOfGrids: 2 });</script></body></html> \ No newline at end of file diff --git a/src/index.jade b/src/index.jade index 4717cc5..55d5560 100644 --- a/src/index.jade +++ b/src/index.jade @@ -1,157 +1,157 @@ doctype html html(lang="en-GB") head meta(http-equiv="Content-Type", content="text/html; charset=utf-8") link(rel="shortcut icon", type="image/x-icon", href="favicon.ico") title #grid // Demo styles style(type="text/css") include ./partial/demo.css // Hashgrid styles style(type="text/css") include ./partial/hashgrid.css body main#content h1 | #grid&nbsp; em v10 p.summary em 30 Nov 2015 span : | #grid (or “Hashgrid”) is a little tool that inserts a&#160; a(href="http://en.wikipedia.org/wiki/Grid_(page_layout)") layout grid | &nbsp;in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit&nbsp; span(class="key") g | on your keyboard. h2 Download p#download - a(href="https://github.com/dotjay/hashgrid/downloads") Download #grid + a(href="https://github.com/dotjay/hashgrid/tags") Download #grid | &nbsp;from&nbsp; a(href="https://github.com/dotjay/hashgrid") GitHub h2#features Features ul li Adaptable for all layout widths and alignments li Adaptable for any vertical rhythm value li Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids li Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters p #grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids. h2#installation Installation ol li h3 Copy the&nbsp; a(href="https://github.com/dotjay/hashgrid/blob/v10/hashgrid.js") hashgrid.js | &nbsp;script to your project li h3 Add this script to your page(s) just before the closing <code>&#60;/body&#62;</code> tag include ./partial/js_code.jade li h3 Add the CSS to your page(s) include ./partial/css_code.jade li h3 Modify #grid to suit your needs p The CSS and JavaScript is annotated to help you. h2#usage Usage p The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first. dl dt <span class="key">g</span> dd Show the grid until you release. dt <span class="key">g</span> + <span class="key">h</span> dd Show and hold the grid (<span class="key">g</span> will remove it again). dt <span class="key">g</span> + <span class="key">f</span> dd Toggle the grid to the foreground and back. Pressing <span class="key">f</span> while the grid is held also works. dt <span class="key">g</span> + <span class="key">j</span> dd Jump to the next grid. Pressing <span class="key">j</span> while the grid is held also works. p <em>Note: Hashgrid remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em> h2#release-notes Release Notes dl dt v10&#8201;&#8212;&#8201;30 Nov 2015 dd Works with vanilla JavaScript - jQuery is no longer required - thanks to <a href="https://github.com/widatama">widatama</a>. dt v9&#8201;&#8212;&#8201;30 May 2013 dd Minor release: Improved example usage to avoid conflicts. dt v8&#8201;&#8212;&#8201;6 Oct 2012 dd ul li Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="http://www.tomarnold.de/">Tom Arnold</a>. li Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="http://lynx.io/">Callum Macrae</a>. li Fixes to cookie handling. Thanks to <a href="http://loonypandora.co.uk/">James Aitken</a>. li Optimisations. dt v7&#8201;&#8212;&#8201;11 Jun 2011 dd Minor release: Updated license references. dt v6&#8201;&#8212;&#8201;10 Jun 2011 dd Minor release: Optimisations (thanks to <a href="http://andrewjaswa.com/">Andrew Jaswa</a> for contributions), and now released under an Apache License. dt v5&#8201;&#8212;&#8201;3 Nov 2010 dd ul li Vertical grid lines can now be set using CSS&#8230; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution. li Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property. li Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback. dt v4&#8201;&#8212;&#8201;29 Mar 2010 dd Fixes for multiple grid support under WebKit (Safari and Chrome). dt v3&#8201;&#8212;&#8201;22 Feb 2010 dd Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms. dt v2&#8201;&#8212;&#8201;2 Feb 2010 dd ul li Keys are now more easily configured (see top of hashgrid.js). li Fixed crash when using with disabled CSS. li Renamed the GridOverlay object to hashgrid. dt v1&#8201;&#8212;&#8201;21 Dec 2009 dd First release. h2#known-issues Known Issues ul li No known issues. h2#license License p Copyright 2013-2022 Jon Gibbins p Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br/> a(href="http://www.apache.org/licenses/LICENSE-2.0") http://www.apache.org/licenses/LICENSE-2.0 p <br/>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. p This essentially means that you&#8217;re free to copy, modify and distribute it for any project so long as you provide clear attribution to the author. <a href="https://dotjay.com/contact">Get in touch</a> if you need a different license. div#footer(role="contentinfo") p #grid was built by <a href="https://dotjay.com/">Jon Gibbins</a> and designed by <a href="https://jontangerine.com/">Jon Tan</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only. // Include the Hashgrid script script(type="text/javascript" src="dist/javascripts/hashgrid.js") // Kick Hashgrid into action script. var hg = new Hashgrid({ numberOfGrids: 2 });
dotjay/hashgrid
35c175a85fa575fdcc2ecc9064c44c4813d35a42
Fix textarea heights
diff --git a/index.html b/index.html index def7fcd..ab4a563 100644 --- a/index.html +++ b/index.html @@ -1,317 +1,317 @@ <!DOCTYPE html><html lang="en-GB"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><link rel="shortcut icon" type="image/x-icon" href="favicon.ico"><title>#grid</title> <!-- Demo styles--> <style type="text/css"> /* Putting inline rules here so the document can be downloaded with style */ body{ font-size: 1em; line-height: 1.25; font-family: Arial, sans-serif; background: White; color: DimGray; margin: 0; padding: 0 20px; } #content{ font-size: 16px; line-height: 20px; position: relative; } #content{ width: 620px; margin: 0 auto; } #footer{ border-top: 1px dotted DarkGray; padding-top: 19px; } h1, h2{ color: Black; font-weight: normal; } h1{ font-size: 36px; line-height: 40px; margin: 40px 0 20px; padding-bottom: 19px; border-bottom: 1px dotted DarkGray; } h1 em{ font-style: normal; color: DarkGray; font-size: 16px; line-height: 20px; margin: 0 0 20px; } h2, h3{ font-size: 16px; font-weight: 700; line-height: 20px; margin: 0 0 20px; } h3{ font-weight: 300; } a:link, a:visited{ color: Black; text-decoration: none; padding: 0 2px; background-color: WhiteSmoke; border-bottom: 1px solid Gold; } a:focus{ outline: none; } a:focus, a:hover, a:active{ background-color: Khaki; border-bottom: 1px solid GoldenRod; } p, ul{ padding: 0; margin: 0 0 20px; } dl, ol{ padding: 0; margin: 0; } ul{ list-style: circle; } ol li{ margin-bottom: 20px; } dd{ margin: 0 0 20px 0; } del{ text-decoration: line-through; opacity: 0.75; } ins{ text-decoration: none; } code{ font-size: 14px; line-height: 1; } textarea{ font-family: 'Courier New', monospace; font-size: 14px; line-height: 20px; display: block; width: 600px; margin: 0 0 20px; -padding: 0 0 0 15px; +padding: 20px 0 0 15px; border: 0; color: Black; background: Gainsboro; border-left: 5px solid DarkGray; } #javascript-code{ -height: 320px; +height: 300px; } #css-code{ -height: 1580px; +height: 1560px; } .summary em{ font-style: normal; position: absolute; color: DarkGray; right: 0; top: 18px; width: 140px; } .summary em span{ position: absolute; left: -9999px; } #download{ line-height: 60px; padding: 0 40px 0 15px; border-left: 5px solid DarkGray; background: Gainsboro; color: DimGray; } span.key{ color: Black; text-transform: uppercase; } </style> <!-- Hashgrid styles--> <style type="text/css"> /** * Hashgrid */ #hashgrid{ /* * Spreads the whole page by default * Adjust to match your container */ /*width: 100%;*/ width: 980px; position: absolute; height: 100%; top: 0; left: 50%; margin-left: -490px; overflow: hidden; } .hashgrid-column-container { position: absolute; height: 100%; width: 100%; top: 0; left: 0; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ .hashgrid__column{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-left: 19px; height: 100%; float: left; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ .hashgrid__row{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option when instantiating Hashgrid. * e.g. * * var hg = new Hashgrid({ * numberOfGrids: 2 * }); */ #hashgrid.hashgrid2, #hashgrid.hashgrid2 .hashgrid-column-container{ /* Container width adjustments */ padding: 0 160px; width: 660px; } #hashgrid.hashgrid2 .hashgrid__column{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </style> </head><body><main id="content"><h1>#grid&nbsp;<em>v10</em></h1><p class="summary"><em>30 Nov 2015<span>:</span></em>#grid (or “Hashgrid”) is a little tool that inserts a&#160;<a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a>&nbsp;in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit&nbsp;<span class="key">g</span> on your keyboard.</p><h2>Download</h2><p id="download"><a href="https://github.com/dotjay/hashgrid/downloads">Download #grid</a>&nbsp;from&nbsp;<a href="https://github.com/dotjay/hashgrid">GitHub</a></p><h2 id="features">Features</h2><ul><li>Adaptable for all layout widths and alignments</li><li>Adaptable for any vertical rhythm value</li><li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li><li>Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters</li></ul><p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p><h2 id="installation">Installation</h2><ol><li><h3>Copy the&nbsp;<a href="https://github.com/dotjay/hashgrid/blob/v9/hashgrid.js">hashgrid.js</a>&nbsp;script to your project</h3></li><li><h3>Add this script to your page(s) just before the closing <code>&#60;/body&#62;</code> tag</h3><textarea id="javascript-code" cols="68" rows="15" readonly="readonly">&#60;!-- Include the hashgrid script --&#62; &#60;script type="text/javascript" src="hashgrid.js"&#62;&#60;/script&#62; &#60;!-- Kick hashgrid into action --&#62; &#60;script type="text/javascript"&#62; var grid = new Hashgrid({ numberOfGrids: 2 }); &#60;/script&#62; &#60;!-- Note: Use window onload if your css is not inlined --&#62; &#60;script type="text/javascript"&#62; window.addEventListener("load", function(event) { var grid = new Hashgrid({ numberOfGrids: 2 }); }); &#60;/script&#62;</textarea></li><li><h3>Add the CSS to your page(s)</h3><textarea id="css-code" cols="68" rows="64" readonly="readonly">/** * Grid */ #hashgrid{ /* * Spreads the whole page by default * Adjust to match your container */ /*width: 100%;*/ width: 980px; position: absolute; height: 100%; top: 0; left: 50%; margin-left: -490px; overflow: hidden; } .hashgrid-column-container { position: absolute; height: 100%; width: 100%; top: 0; left: 0; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ .hashgrid__column{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-left: 19px; height: 100%; float: left; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ .hashgrid__row{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option when instantiating hashgrid. * e.g. * * var hg = new Hashgrid({ * numberOfGrids: 2 * }); */ #hashgrid.hashgrid2, #hashgrid.hashgrid2 .hashgrid-column-container{ /* Container width adjustments */ padding: 0 160px; width: 660px; } #hashgrid.hashgrid2 .hashgrid__column{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </textarea></li><li><h3>Modify #grid to suit your needs</h3><p>The CSS and JavaScript is annotated to help you.</p></li></ol><h2 id="usage">Usage</h2><p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p><dl><dt><span class="key">g</span></dt><dd>Show the grid until you release.</dd><dt><span class="key">g</span> + <span class="key">h</span></dt><dd>Show and hold the grid (<span class="key">g</span> will remove it again).</dd><dt><span class="key">g</span> + <span class="key">f</span></dt><dd>Toggle the grid to the foreground and back. Pressing <span class="key">f</span> while the grid is held also works.</dd><dt><span class="key">g</span> + <span class="key">j</span></dt><dd>Jump to the next grid. Pressing <span class="key">j</span> while the grid is held also works.</dd></dl><p><em>Note: Hashgrid remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em></p><h2 id="release-notes">Release Notes</h2><dl><dt>v10&#8201;&#8212;&#8201;30 Nov 2015</dt><dd>Works with vanilla JavaScript - jQuery is no longer required - thanks to <a href="https://github.com/widatama">widatama</a>.</dd><dt>v9&#8201;&#8212;&#8201;30 May 2013</dt><dd>Minor release: Improved example usage to avoid conflicts.</dd><dt>v8&#8201;&#8212;&#8201;6 Oct 2012</dt><dd><ul><li>Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="http://www.tomarnold.de/">Tom Arnold</a>.</li><li>Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="http://lynx.io/">Callum Macrae</a>.</li><li>Fixes to cookie handling. Thanks to <a href="http://loonypandora.co.uk/">James Aitken</a>.</li><li>Optimisations.</li></ul></dd><dt>v7&#8201;&#8212;&#8201;11 Jun 2011</dt><dd>Minor release: Updated license references.</dd><dt>v6&#8201;&#8212;&#8201;10 Jun 2011</dt><dd>Minor release: Optimisations (thanks to <a href="http://andrewjaswa.com/">Andrew Jaswa</a> for contributions), and now released under an Apache License.</dd><dt>v5&#8201;&#8212;&#8201;3 Nov 2010</dt><dd><ul><li>Vertical grid lines can now be set using CSS&#8230; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution.</li><li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li><li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback.</li></ul></dd><dt>v4&#8201;&#8212;&#8201;29 Mar 2010</dt><dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd><dt>v3&#8201;&#8212;&#8201;22 Feb 2010</dt><dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd><dt>v2&#8201;&#8212;&#8201;2 Feb 2010</dt><dd><ul><li>Keys are now more easily configured (see top of hashgrid.js).</li><li>Fixed crash when using with disabled CSS.</li><li>Renamed the GridOverlay object to hashgrid.</li></ul></dd><dt>v1&#8201;&#8212;&#8201;21 Dec 2009</dt><dd>First release.</dd></dl><h2 id="known-issues">Known Issues</h2><ul><li>No known issues.</li></ul><h2 id="license">License</h2><p>Copyright 2013-2022 Jon Gibbins</p><p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br/></p><a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a><p><br/>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.</p><p>This essentially means that you&#8217;re free to copy, modify and distribute it for any project so long as you provide clear attribution to the author. <a href="https://dotjay.com/contact">Get in touch</a> if you need a different license.</p><div id="footer" role="contentinfo"><p>#grid was built by <a href="https://dotjay.com/">Jon Gibbins</a> and designed by <a href="https://jontangerine.com/">Jon Tan</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p></div></main><!-- Include the hashgrid script--><script type="text/javascript" src="dist/javascripts/hashgrid.js"></script><!-- Kick hashgrid into action--><script>var hg = new Hashgrid({ numberOfGrids: 2 });</script></body></html> \ No newline at end of file diff --git a/src/partial/demo.css b/src/partial/demo.css index d842349..388bc0b 100644 --- a/src/partial/demo.css +++ b/src/partial/demo.css @@ -1,138 +1,138 @@ /* Putting inline rules here so the document can be downloaded with style */ body{ font-size: 1em; line-height: 1.25; font-family: Arial, sans-serif; background: White; color: DimGray; margin: 0; padding: 0 20px; } #content{ font-size: 16px; line-height: 20px; position: relative; } #content{ width: 620px; margin: 0 auto; } #footer{ border-top: 1px dotted DarkGray; padding-top: 19px; } h1, h2{ color: Black; font-weight: normal; } h1{ font-size: 36px; line-height: 40px; margin: 40px 0 20px; padding-bottom: 19px; border-bottom: 1px dotted DarkGray; } h1 em{ font-style: normal; color: DarkGray; font-size: 16px; line-height: 20px; margin: 0 0 20px; } h2, h3{ font-size: 16px; font-weight: 700; line-height: 20px; margin: 0 0 20px; } h3{ font-weight: 300; } a:link, a:visited{ color: Black; text-decoration: none; padding: 0 2px; background-color: WhiteSmoke; border-bottom: 1px solid Gold; } a:focus{ outline: none; } a:focus, a:hover, a:active{ background-color: Khaki; border-bottom: 1px solid GoldenRod; } p, ul{ padding: 0; margin: 0 0 20px; } dl, ol{ padding: 0; margin: 0; } ul{ list-style: circle; } ol li{ margin-bottom: 20px; } dd{ margin: 0 0 20px 0; } del{ text-decoration: line-through; opacity: 0.75; } ins{ text-decoration: none; } code{ font-size: 14px; line-height: 1; } textarea{ font-family: 'Courier New', monospace; font-size: 14px; line-height: 20px; display: block; width: 600px; margin: 0 0 20px; -padding: 0 0 0 15px; +padding: 20px 0 0 15px; border: 0; color: Black; background: Gainsboro; border-left: 5px solid DarkGray; } #javascript-code{ -height: 320px; +height: 300px; } #css-code{ -height: 1580px; +height: 1560px; } .summary em{ font-style: normal; position: absolute; color: DarkGray; right: 0; top: 18px; width: 140px; } .summary em span{ position: absolute; left: -9999px; } #download{ line-height: 60px; padding: 0 40px 0 15px; border-left: 5px solid DarkGray; background: Gainsboro; color: DimGray; } span.key{ color: Black; text-transform: uppercase; }
dotjay/hashgrid
2c6cea7db683a62edfbfbdcb7493b7a916a34db2
Bring back the favicon on Github Pages
diff --git a/index.html b/index.html index f5058ed..def7fcd 100644 --- a/index.html +++ b/index.html @@ -1,317 +1,317 @@ -<!DOCTYPE html><html lang="en-GB"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>#grid</title> +<!DOCTYPE html><html lang="en-GB"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><link rel="shortcut icon" type="image/x-icon" href="favicon.ico"><title>#grid</title> <!-- Demo styles--> <style type="text/css"> /* Putting inline rules here so the document can be downloaded with style */ body{ font-size: 1em; line-height: 1.25; font-family: Arial, sans-serif; background: White; color: DimGray; margin: 0; padding: 0 20px; } #content{ font-size: 16px; line-height: 20px; position: relative; } #content{ width: 620px; margin: 0 auto; } #footer{ border-top: 1px dotted DarkGray; padding-top: 19px; } h1, h2{ color: Black; font-weight: normal; } h1{ font-size: 36px; line-height: 40px; margin: 40px 0 20px; padding-bottom: 19px; border-bottom: 1px dotted DarkGray; } h1 em{ font-style: normal; color: DarkGray; font-size: 16px; line-height: 20px; margin: 0 0 20px; } h2, h3{ font-size: 16px; font-weight: 700; line-height: 20px; margin: 0 0 20px; } h3{ font-weight: 300; } a:link, a:visited{ color: Black; text-decoration: none; padding: 0 2px; background-color: WhiteSmoke; border-bottom: 1px solid Gold; } a:focus{ outline: none; } a:focus, a:hover, a:active{ background-color: Khaki; border-bottom: 1px solid GoldenRod; } p, ul{ padding: 0; margin: 0 0 20px; } dl, ol{ padding: 0; margin: 0; } ul{ list-style: circle; } ol li{ margin-bottom: 20px; } dd{ margin: 0 0 20px 0; } del{ text-decoration: line-through; opacity: 0.75; } ins{ text-decoration: none; } code{ font-size: 14px; line-height: 1; } textarea{ font-family: 'Courier New', monospace; font-size: 14px; line-height: 20px; display: block; width: 600px; margin: 0 0 20px; padding: 0 0 0 15px; border: 0; color: Black; background: Gainsboro; border-left: 5px solid DarkGray; } #javascript-code{ height: 320px; } #css-code{ height: 1580px; } .summary em{ font-style: normal; position: absolute; color: DarkGray; right: 0; top: 18px; width: 140px; } .summary em span{ position: absolute; left: -9999px; } #download{ line-height: 60px; padding: 0 40px 0 15px; border-left: 5px solid DarkGray; background: Gainsboro; color: DimGray; } span.key{ color: Black; text-transform: uppercase; } </style> <!-- Hashgrid styles--> <style type="text/css"> /** * Hashgrid */ #hashgrid{ /* * Spreads the whole page by default * Adjust to match your container */ /*width: 100%;*/ width: 980px; position: absolute; height: 100%; top: 0; left: 50%; margin-left: -490px; overflow: hidden; } .hashgrid-column-container { position: absolute; height: 100%; width: 100%; top: 0; left: 0; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ .hashgrid__column{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-left: 19px; height: 100%; float: left; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ .hashgrid__row{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option when instantiating Hashgrid. * e.g. * * var hg = new Hashgrid({ * numberOfGrids: 2 * }); */ #hashgrid.hashgrid2, #hashgrid.hashgrid2 .hashgrid-column-container{ /* Container width adjustments */ padding: 0 160px; width: 660px; } #hashgrid.hashgrid2 .hashgrid__column{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </style> </head><body><main id="content"><h1>#grid&nbsp;<em>v10</em></h1><p class="summary"><em>30 Nov 2015<span>:</span></em>#grid (or “Hashgrid”) is a little tool that inserts a&#160;<a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a>&nbsp;in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit&nbsp;<span class="key">g</span> on your keyboard.</p><h2>Download</h2><p id="download"><a href="https://github.com/dotjay/hashgrid/downloads">Download #grid</a>&nbsp;from&nbsp;<a href="https://github.com/dotjay/hashgrid">GitHub</a></p><h2 id="features">Features</h2><ul><li>Adaptable for all layout widths and alignments</li><li>Adaptable for any vertical rhythm value</li><li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li><li>Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters</li></ul><p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p><h2 id="installation">Installation</h2><ol><li><h3>Copy the&nbsp;<a href="https://github.com/dotjay/hashgrid/blob/v9/hashgrid.js">hashgrid.js</a>&nbsp;script to your project</h3></li><li><h3>Add this script to your page(s) just before the closing <code>&#60;/body&#62;</code> tag</h3><textarea id="javascript-code" cols="68" rows="15" readonly="readonly">&#60;!-- Include the hashgrid script --&#62; &#60;script type="text/javascript" src="hashgrid.js"&#62;&#60;/script&#62; &#60;!-- Kick hashgrid into action --&#62; &#60;script type="text/javascript"&#62; var grid = new Hashgrid({ numberOfGrids: 2 }); &#60;/script&#62; &#60;!-- Note: Use window onload if your css is not inlined --&#62; &#60;script type="text/javascript"&#62; window.addEventListener("load", function(event) { var grid = new Hashgrid({ numberOfGrids: 2 }); }); &#60;/script&#62;</textarea></li><li><h3>Add the CSS to your page(s)</h3><textarea id="css-code" cols="68" rows="64" readonly="readonly">/** * Grid */ #hashgrid{ /* * Spreads the whole page by default * Adjust to match your container */ /*width: 100%;*/ width: 980px; position: absolute; height: 100%; top: 0; left: 50%; margin-left: -490px; overflow: hidden; } .hashgrid-column-container { position: absolute; height: 100%; width: 100%; top: 0; left: 0; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ .hashgrid__column{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-left: 19px; height: 100%; float: left; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ .hashgrid__row{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option when instantiating hashgrid. * e.g. * * var hg = new Hashgrid({ * numberOfGrids: 2 * }); */ #hashgrid.hashgrid2, #hashgrid.hashgrid2 .hashgrid-column-container{ /* Container width adjustments */ padding: 0 160px; width: 660px; } #hashgrid.hashgrid2 .hashgrid__column{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </textarea></li><li><h3>Modify #grid to suit your needs</h3><p>The CSS and JavaScript is annotated to help you.</p></li></ol><h2 id="usage">Usage</h2><p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p><dl><dt><span class="key">g</span></dt><dd>Show the grid until you release.</dd><dt><span class="key">g</span> + <span class="key">h</span></dt><dd>Show and hold the grid (<span class="key">g</span> will remove it again).</dd><dt><span class="key">g</span> + <span class="key">f</span></dt><dd>Toggle the grid to the foreground and back. Pressing <span class="key">f</span> while the grid is held also works.</dd><dt><span class="key">g</span> + <span class="key">j</span></dt><dd>Jump to the next grid. Pressing <span class="key">j</span> while the grid is held also works.</dd></dl><p><em>Note: Hashgrid remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em></p><h2 id="release-notes">Release Notes</h2><dl><dt>v10&#8201;&#8212;&#8201;30 Nov 2015</dt><dd>Works with vanilla JavaScript - jQuery is no longer required - thanks to <a href="https://github.com/widatama">widatama</a>.</dd><dt>v9&#8201;&#8212;&#8201;30 May 2013</dt><dd>Minor release: Improved example usage to avoid conflicts.</dd><dt>v8&#8201;&#8212;&#8201;6 Oct 2012</dt><dd><ul><li>Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="http://www.tomarnold.de/">Tom Arnold</a>.</li><li>Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="http://lynx.io/">Callum Macrae</a>.</li><li>Fixes to cookie handling. Thanks to <a href="http://loonypandora.co.uk/">James Aitken</a>.</li><li>Optimisations.</li></ul></dd><dt>v7&#8201;&#8212;&#8201;11 Jun 2011</dt><dd>Minor release: Updated license references.</dd><dt>v6&#8201;&#8212;&#8201;10 Jun 2011</dt><dd>Minor release: Optimisations (thanks to <a href="http://andrewjaswa.com/">Andrew Jaswa</a> for contributions), and now released under an Apache License.</dd><dt>v5&#8201;&#8212;&#8201;3 Nov 2010</dt><dd><ul><li>Vertical grid lines can now be set using CSS&#8230; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution.</li><li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li><li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback.</li></ul></dd><dt>v4&#8201;&#8212;&#8201;29 Mar 2010</dt><dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd><dt>v3&#8201;&#8212;&#8201;22 Feb 2010</dt><dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd><dt>v2&#8201;&#8212;&#8201;2 Feb 2010</dt><dd><ul><li>Keys are now more easily configured (see top of hashgrid.js).</li><li>Fixed crash when using with disabled CSS.</li><li>Renamed the GridOverlay object to hashgrid.</li></ul></dd><dt>v1&#8201;&#8212;&#8201;21 Dec 2009</dt><dd>First release.</dd></dl><h2 id="known-issues">Known Issues</h2><ul><li>No known issues.</li></ul><h2 id="license">License</h2><p>Copyright 2013-2022 Jon Gibbins</p><p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br/></p><a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a><p><br/>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.</p><p>This essentially means that you&#8217;re free to copy, modify and distribute it for any project so long as you provide clear attribution to the author. <a href="https://dotjay.com/contact">Get in touch</a> if you need a different license.</p><div id="footer" role="contentinfo"><p>#grid was built by <a href="https://dotjay.com/">Jon Gibbins</a> and designed by <a href="https://jontangerine.com/">Jon Tan</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p></div></main><!-- Include the hashgrid script--><script type="text/javascript" src="dist/javascripts/hashgrid.js"></script><!-- Kick hashgrid into action--><script>var hg = new Hashgrid({ numberOfGrids: 2 });</script></body></html> \ No newline at end of file diff --git a/src/index.jade b/src/index.jade index 22ce641..4717cc5 100644 --- a/src/index.jade +++ b/src/index.jade @@ -1,156 +1,157 @@ doctype html html(lang="en-GB") head meta(http-equiv="Content-Type", content="text/html; charset=utf-8") + link(rel="shortcut icon", type="image/x-icon", href="favicon.ico") title #grid // Demo styles style(type="text/css") include ./partial/demo.css // Hashgrid styles style(type="text/css") include ./partial/hashgrid.css body main#content h1 | #grid&nbsp; em v10 p.summary em 30 Nov 2015 span : | #grid (or “Hashgrid”) is a little tool that inserts a&#160; a(href="http://en.wikipedia.org/wiki/Grid_(page_layout)") layout grid | &nbsp;in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit&nbsp; span(class="key") g | on your keyboard. h2 Download p#download a(href="https://github.com/dotjay/hashgrid/downloads") Download #grid | &nbsp;from&nbsp; a(href="https://github.com/dotjay/hashgrid") GitHub h2#features Features ul li Adaptable for all layout widths and alignments li Adaptable for any vertical rhythm value li Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids li Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters p #grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids. h2#installation Installation ol li h3 Copy the&nbsp; a(href="https://github.com/dotjay/hashgrid/blob/v10/hashgrid.js") hashgrid.js | &nbsp;script to your project li h3 Add this script to your page(s) just before the closing <code>&#60;/body&#62;</code> tag include ./partial/js_code.jade li h3 Add the CSS to your page(s) include ./partial/css_code.jade li h3 Modify #grid to suit your needs p The CSS and JavaScript is annotated to help you. h2#usage Usage p The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first. dl dt <span class="key">g</span> dd Show the grid until you release. dt <span class="key">g</span> + <span class="key">h</span> dd Show and hold the grid (<span class="key">g</span> will remove it again). dt <span class="key">g</span> + <span class="key">f</span> dd Toggle the grid to the foreground and back. Pressing <span class="key">f</span> while the grid is held also works. dt <span class="key">g</span> + <span class="key">j</span> dd Jump to the next grid. Pressing <span class="key">j</span> while the grid is held also works. p <em>Note: Hashgrid remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em> h2#release-notes Release Notes dl dt v10&#8201;&#8212;&#8201;30 Nov 2015 dd Works with vanilla JavaScript - jQuery is no longer required - thanks to <a href="https://github.com/widatama">widatama</a>. dt v9&#8201;&#8212;&#8201;30 May 2013 dd Minor release: Improved example usage to avoid conflicts. dt v8&#8201;&#8212;&#8201;6 Oct 2012 dd ul li Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="http://www.tomarnold.de/">Tom Arnold</a>. li Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="http://lynx.io/">Callum Macrae</a>. li Fixes to cookie handling. Thanks to <a href="http://loonypandora.co.uk/">James Aitken</a>. li Optimisations. dt v7&#8201;&#8212;&#8201;11 Jun 2011 dd Minor release: Updated license references. dt v6&#8201;&#8212;&#8201;10 Jun 2011 dd Minor release: Optimisations (thanks to <a href="http://andrewjaswa.com/">Andrew Jaswa</a> for contributions), and now released under an Apache License. dt v5&#8201;&#8212;&#8201;3 Nov 2010 dd ul li Vertical grid lines can now be set using CSS&#8230; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution. li Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property. li Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback. dt v4&#8201;&#8212;&#8201;29 Mar 2010 dd Fixes for multiple grid support under WebKit (Safari and Chrome). dt v3&#8201;&#8212;&#8201;22 Feb 2010 dd Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms. dt v2&#8201;&#8212;&#8201;2 Feb 2010 dd ul li Keys are now more easily configured (see top of hashgrid.js). li Fixed crash when using with disabled CSS. li Renamed the GridOverlay object to hashgrid. dt v1&#8201;&#8212;&#8201;21 Dec 2009 dd First release. h2#known-issues Known Issues ul li No known issues. h2#license License p Copyright 2013-2022 Jon Gibbins p Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br/> a(href="http://www.apache.org/licenses/LICENSE-2.0") http://www.apache.org/licenses/LICENSE-2.0 p <br/>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. p This essentially means that you&#8217;re free to copy, modify and distribute it for any project so long as you provide clear attribution to the author. <a href="https://dotjay.com/contact">Get in touch</a> if you need a different license. div#footer(role="contentinfo") p #grid was built by <a href="https://dotjay.com/">Jon Gibbins</a> and designed by <a href="https://jontangerine.com/">Jon Tan</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only. // Include the Hashgrid script script(type="text/javascript" src="dist/javascripts/hashgrid.js") // Kick Hashgrid into action script. var hg = new Hashgrid({ numberOfGrids: 2 });
dotjay/hashgrid
55d26dc34a147c4c341ed2f6def966c5bfd3a0b7
Copyright year
diff --git a/README.md b/README.md index 5fc3a45..6810e8f 100644 --- a/README.md +++ b/README.md @@ -1,74 +1,74 @@ # #grid # A little tool that inserts a layout grid in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. ## Features ## * Adaptable for all layout widths and alignments * Adaptable for any vertical rhythm value * Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids * Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters ## Install ## Download the latest release from: https://github.com/dotjay/hashgrid/tags Install using [Bower](http://bower.io/): ```bash bower install hashgrid#v10 ``` Notes on usage can be found at [dotjay.github.io/hashgrid/#installation](https://dotjay.github.io/hashgrid/#installation). ## Please note ## The latest version of #grid is maintained on Github, and its official web page is: [dotjay.github.io/hashgrid/](https://dotjay.github.io/hashgrid/) It is no longer hosted at hashgrid.com, which is now defunct. ## Development ## Install dependencies ```bash npm install ``` Run tests ```bash npm test ``` Build for production ```bash # This will build hashgrid into dist folder grunt # This will build hashgrid and then turn on the watcher for auto building grunt dev ``` ## License ## -Copyright 2013-2018 Jon Gibbins +Copyright 2013-2022 Jon Gibbins Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -- This essentially means that you're free to copy, modify and distribute it for any project so long as you provide clear attribution to the author. Get in touch if you need a different license. https://dotjay.com/contact
dotjay/hashgrid
09e56aea5e0bf57d847e8e0f8ad4b153af23f612
Remove ancient issues for ancient web browsers. Add note on intent to modernise.
diff --git a/index.htm b/index.htm index b6d98c2..8b7a147 100644 --- a/index.htm +++ b/index.htm @@ -1,472 +1,470 @@ <!doctype html> <html lang="en-GB"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link rel="shortcut icon" type="image/x-icon" href="favicon.ico"> <title>#grid</title> <style> /* Putting inline rules here so the document can be downloaded with style */ body{ font-size: 1em; line-height: 1.25; font-family: Arial, sans-serif; background: White; color: DimGray; margin: 0; padding: 0 20px; } #content{ font-size: 16px; line-height: 20px; position: relative; } #content{ width: 620px; margin: 0 auto; } #footer{ border-top: 1px dotted DarkGray; padding-top: 19px; } h1, h2{ color: Black; font-weight: normal; } h1{ font-size: 36px; line-height: 40px; margin: 40px 0 20px; padding-bottom: 19px; border-bottom: 1px dotted DarkGray; } h1 em{ font-style: normal; color: DarkGray; font-size: 16px; line-height: 20px; margin: 0 0 20px; } h2, h3{ font-size: 16px; font-weight: 700; line-height: 20px; margin: 0 0 20px; } h3{ font-weight: 300; } a:link, a:visited{ color: Black; text-decoration: none; padding: 0 2px; background-color: WhiteSmoke; border-bottom: 1px solid Gold; } a:focus{ outline: none; } a:focus, a:hover, a:active{ background-color: Khaki; border-bottom: 1px solid GoldenRod; } p, ul{ padding: 0; margin: 0 0 20px; } dl, ol{ padding: 0; margin: 0; } ul{ list-style: circle; } ol li{ margin-bottom: 20px; } dd{ margin: 0 0 20px 0; } del{ text-decoration: line-through; opacity: 0.75; } ins{ text-decoration: none; } code{ font-size: 14px; line-height: 1; } textarea{ font-family: 'Courier New', monospace; font-size: 14px; line-height: 20px; display: block; width: 600px; margin: 0 0 20px; padding: 0 0 0 15px; border: 0; color: Black; background: Gainsboro; border-left: 5px solid DarkGray; } #javascript-code{ height: 280px; } #css-code{ height: 1300px; } .summary em{ font-style: normal; position: absolute; color: DarkGray; right: 0; top: 18px; width: 140px; } .summary em span{ position: absolute; left: -9999px; } #download{ line-height: 60px; padding: 0 40px 0 15px; border-left: 5px solid DarkGray; background: Gainsboro; color: DimGray; } span.key{ color: Black; text-transform: uppercase; } </style> <!-- Set styles --> <style> /** * Grid */ #grid{ /* Dimensions - same width as your grid with gutters */ width: 980px; /* Grid (left-aligned) position: absolute; top: 0; left: 0; */ /* Grid (centered) */ position: absolute; top: 0; left: 50%; margin-left: -490px; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ #grid div.vert{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-right: 19px; } #grid div.vert.first-line{ margin-left: 19px; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ #grid div.horiz{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option in the hashgrid.js file. */ #grid.grid-1 div.vert{ /* Vertical grid line colour for grid 1 */ border-color: darkturquoise; } #grid.grid-2{ /* Adjustments */ padding: 0 160px; width: 660px; } #grid.grid-2 div.vert{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </style> </head> <body> <div id="content" role="main"> <h1>#grid <em>v9</em></h1> <p class="summary"><em>30 May 2013<span>:</span></em> #grid (or &#8220;Hashgrid&#8221;) is a little tool that inserts a <a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a> in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit <span class="key">G</span> on your keyboard.</p> <h2>Download</h2> <p id="download"><a href="https://github.com/dotjay/hashgrid/downloads">Download #grid</a> from <a href="https://github.com/dotjay/hashgrid">GitHub</a></p> <h2 id="features">Features</h2> <ul> <li>Adaptable for all layout widths and alignments</li> <li>Adaptable for any vertical rhythm value</li> <li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li> <li>Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters</li> </ul> <p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p> <h2 id="installation">Installation</h2> <ol> <li><h3>Copy the <a href="https://github.com/dotjay/hashgrid/blob/v9/hashgrid.js">hashgrid.js</a> script to your project</h3></li> <li><h3>Add the script to your page(s) just inside the <code>&#60;/body&#62;</code> tag</h3> <textarea id="javascript-code" cols="68" rows="14" readonly="readonly"> &#60;!-- Grab latest version of jQuery --&#62; &#60;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"&#62;&#60;/script&#62; &#60;!-- Include the hashgrid script --&#62; &#60;script src="hashgrid.js"&#62;&#60;/script&#62; &#60;!-- Kick hashgrid into action --&#62; &#60;script&#62; var grid = new hashgrid({ numberOfGrids: 2 }); &#60;/script&#62;</textarea></li> <li><h3>Add the CSS to your page(s)</h3> <textarea id="css-code" cols="68" rows="64" readonly="readonly"> /** * Grid */ #grid{ /* Dimensions - same width as your grid with gutters */ width: 980px; /* Grid (left-aligned) position: absolute; top: 0; left: 0; */ /* Grid (centered) */ position: absolute; top: 0; left: 50%; margin-left: -490px; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ #grid div.vert{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-right: 19px; } #grid div.vert.first-line{ margin-left: 19px; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ #grid div.horiz{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option in the hashgrid.js file. */ #grid.grid-1 div.vert{ /* Vertical grid line colour for grid 1 */ border-color: darkturquoise; } #grid.grid-2{ /* Adjustments */ padding: 0 160px; width: 660px; } #grid.grid-2 div.vert{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </textarea></li> <li><h3>Modify #grid to suit your needs</h3> <p>The CSS and JavaScript is annotated to help you.</p></li> </ol> <h2 id="usage">Usage</h2> <p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p> <dl> <dt><span class="key">G</span></dt> <dd>Show the grid until you release.</dd> <dt><span class="key">G</span> + <span class="key">H</span></dt> <dd>Show and hold the grid (<span class="key">G</span> will remove it again).</dd> <dt><span class="key">G</span> + <span class="key">F</span></dt> <dd>Toggle the grid to the foreground and back. Pressing <span class="key">F</span> while the grid is held also works.</dd> <dt><span class="key">G</span> + <span class="key">J</span></dt> <dd>Jump to the next grid. Pressing <span class="key">J</span> while the grid is held also works.</dd> </dl> <p><em>N.B. A cookie conveniently remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page except in Chrome v4, Safari v4, Firefox v3.6, or more recent versions.</em></p> <h2 id="release-notes">Release Notes</h2> <dl> <dt>v9&#8201;&#8212;&#8201;30 May 2013</dt> <dd>Minor release: Improved example usage to avoid conflicts.</dd> <dt>v8&#8201;&#8212;&#8201;6 Oct 2012</dt> <dd> <ul> <li>Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="http://www.tomarnold.de/">Tom Arnold</a>.</li> <li>Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="http://lynx.io/">Callum Macrae</a>.</li> <li>Fixes to cookie handling. Thanks to <a href="http://loonypandora.co.uk/">James Aitken</a>.</li> <li>Optimisations.</li> </ul> </dd> <dt>v7&#8201;&#8212;&#8201;11 Jun 2011</dt> <dd>Minor release: Updated license references.</dd> <dt>v6&#8201;&#8212;&#8201;10 Jun 2011</dt> <dd>Minor release: Optimisations (thanks to <a href="http://andrewjaswa.com/">Andrew Jaswa</a> for contributions), and now released under an Apache License.</dd> <dt>v5&#8201;&#8212;&#8201;3 Nov 2010</dt> <dd> <ul> <li>Vertical grid lines can now be set using CSS&#8230; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution.</li> <li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li> <li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback.</li> </ul> </dd> <dt>v4&#8201;&#8212;&#8201;29 Mar 2010</dt> <dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd> <dt>v3&#8201;&#8212;&#8201;22 Feb 2010</dt> <dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd> <dt>v2&#8201;&#8212;&#8201;2 Feb 2010</dt> <dd> <ul> <li>Keys are now more easily configured (see top of hashgrid.js).</li> <li>Fixed crash when using with disabled CSS.</li> <li>Renamed the GridOverlay object to hashgrid.</li> </ul> </dd> <dt>v1&#8201;&#8212;&#8201;21 Dec 2009</dt> <dd>First release.</dd> </dl> <h2 id="known-issues">Known Issues</h2> <ul> -<li><del>IE 8: Fully functional, but the default <span class="key">ALT</span> + <span class="key">G</span> + <span class="key">ENTER</span> shortcut puts IE into full screen mode. Hit <span class="key">ALT</span> + <span class="key">ENTER</span> to toggle full screen mode off again.</del><ins datetime="2010-02-22"> The default keyboard shortcuts have been changed.</ins></li> -<li>IE 6: The grid is always in the foreground.</li> -<li>Opera 9/10: Using <span class="key">CTRL</span> or <span class="key">ALT</span> as a modifier key will not work due to different key handling by the browser.</li> +<li>Relies on an old jQuery library. Currently working on a modern, vanilla JavaScript version.</li> </ul> <h2 id="license">License</h2> <p>Copyright 2013-2018 Jon Gibbins</p> <p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br /><br /> <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a></p> <p>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.</p> <p>This essentially means that you&#8217;re free to copy, modify and distribute it for any project so long as you provide clear attribution to the author. <a href="https://dotjay.com/contact">Get in touch</a> if you need a different license.</p> <div id="footer" role="contentinfo"> <p>#grid was built by <a href="https://dotjay.com/">Jon Gibbins</a> and designed by <a href="http://jontangerine.com/">Jon Tan</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p> </div> </div> <!-- Grab latest version of jQuery --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <!-- Include the hashgrid script --> <script src="hashgrid.js"></script> <!-- Kick hashgrid into action --> <script> var grid = new hashgrid({ numberOfGrids: 2 }); </script> </body> </html>
dotjay/hashgrid
3c4243d216a98fb9649b9f2f1f2235bfd675814b
Latest jQuery v1. Use HTTPS.
diff --git a/index.htm b/index.htm index ff7d393..b6d98c2 100644 --- a/index.htm +++ b/index.htm @@ -1,472 +1,472 @@ <!doctype html> <html lang="en-GB"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link rel="shortcut icon" type="image/x-icon" href="favicon.ico"> <title>#grid</title> <style> /* Putting inline rules here so the document can be downloaded with style */ body{ font-size: 1em; line-height: 1.25; font-family: Arial, sans-serif; background: White; color: DimGray; margin: 0; padding: 0 20px; } #content{ font-size: 16px; line-height: 20px; position: relative; } #content{ width: 620px; margin: 0 auto; } #footer{ border-top: 1px dotted DarkGray; padding-top: 19px; } h1, h2{ color: Black; font-weight: normal; } h1{ font-size: 36px; line-height: 40px; margin: 40px 0 20px; padding-bottom: 19px; border-bottom: 1px dotted DarkGray; } h1 em{ font-style: normal; color: DarkGray; font-size: 16px; line-height: 20px; margin: 0 0 20px; } h2, h3{ font-size: 16px; font-weight: 700; line-height: 20px; margin: 0 0 20px; } h3{ font-weight: 300; } a:link, a:visited{ color: Black; text-decoration: none; padding: 0 2px; background-color: WhiteSmoke; border-bottom: 1px solid Gold; } a:focus{ outline: none; } a:focus, a:hover, a:active{ background-color: Khaki; border-bottom: 1px solid GoldenRod; } p, ul{ padding: 0; margin: 0 0 20px; } dl, ol{ padding: 0; margin: 0; } ul{ list-style: circle; } ol li{ margin-bottom: 20px; } dd{ margin: 0 0 20px 0; } del{ text-decoration: line-through; opacity: 0.75; } ins{ text-decoration: none; } code{ font-size: 14px; line-height: 1; } textarea{ font-family: 'Courier New', monospace; font-size: 14px; line-height: 20px; display: block; width: 600px; margin: 0 0 20px; padding: 0 0 0 15px; border: 0; color: Black; background: Gainsboro; border-left: 5px solid DarkGray; } #javascript-code{ height: 280px; } #css-code{ height: 1300px; } .summary em{ font-style: normal; position: absolute; color: DarkGray; right: 0; top: 18px; width: 140px; } .summary em span{ position: absolute; left: -9999px; } #download{ line-height: 60px; padding: 0 40px 0 15px; border-left: 5px solid DarkGray; background: Gainsboro; color: DimGray; } span.key{ color: Black; text-transform: uppercase; } </style> <!-- Set styles --> <style> /** * Grid */ #grid{ /* Dimensions - same width as your grid with gutters */ width: 980px; /* Grid (left-aligned) position: absolute; top: 0; left: 0; */ /* Grid (centered) */ position: absolute; top: 0; left: 50%; margin-left: -490px; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ #grid div.vert{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-right: 19px; } #grid div.vert.first-line{ margin-left: 19px; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ #grid div.horiz{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option in the hashgrid.js file. */ #grid.grid-1 div.vert{ /* Vertical grid line colour for grid 1 */ border-color: darkturquoise; } #grid.grid-2{ /* Adjustments */ padding: 0 160px; width: 660px; } #grid.grid-2 div.vert{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </style> </head> <body> <div id="content" role="main"> <h1>#grid <em>v9</em></h1> <p class="summary"><em>30 May 2013<span>:</span></em> #grid (or &#8220;Hashgrid&#8221;) is a little tool that inserts a <a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a> in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit <span class="key">G</span> on your keyboard.</p> <h2>Download</h2> <p id="download"><a href="https://github.com/dotjay/hashgrid/downloads">Download #grid</a> from <a href="https://github.com/dotjay/hashgrid">GitHub</a></p> <h2 id="features">Features</h2> <ul> <li>Adaptable for all layout widths and alignments</li> <li>Adaptable for any vertical rhythm value</li> <li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li> <li>Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters</li> </ul> <p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p> <h2 id="installation">Installation</h2> <ol> <li><h3>Copy the <a href="https://github.com/dotjay/hashgrid/blob/v9/hashgrid.js">hashgrid.js</a> script to your project</h3></li> <li><h3>Add the script to your page(s) just inside the <code>&#60;/body&#62;</code> tag</h3> <textarea id="javascript-code" cols="68" rows="14" readonly="readonly"> &#60;!-- Grab latest version of jQuery --&#62; -&#60;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"&#62;&#60;/script&#62; +&#60;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"&#62;&#60;/script&#62; &#60;!-- Include the hashgrid script --&#62; &#60;script src="hashgrid.js"&#62;&#60;/script&#62; &#60;!-- Kick hashgrid into action --&#62; &#60;script&#62; var grid = new hashgrid({ numberOfGrids: 2 }); &#60;/script&#62;</textarea></li> <li><h3>Add the CSS to your page(s)</h3> <textarea id="css-code" cols="68" rows="64" readonly="readonly"> /** * Grid */ #grid{ /* Dimensions - same width as your grid with gutters */ width: 980px; /* Grid (left-aligned) position: absolute; top: 0; left: 0; */ /* Grid (centered) */ position: absolute; top: 0; left: 50%; margin-left: -490px; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ #grid div.vert{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-right: 19px; } #grid div.vert.first-line{ margin-left: 19px; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ #grid div.horiz{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option in the hashgrid.js file. */ #grid.grid-1 div.vert{ /* Vertical grid line colour for grid 1 */ border-color: darkturquoise; } #grid.grid-2{ /* Adjustments */ padding: 0 160px; width: 660px; } #grid.grid-2 div.vert{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </textarea></li> <li><h3>Modify #grid to suit your needs</h3> <p>The CSS and JavaScript is annotated to help you.</p></li> </ol> <h2 id="usage">Usage</h2> <p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p> <dl> <dt><span class="key">G</span></dt> <dd>Show the grid until you release.</dd> <dt><span class="key">G</span> + <span class="key">H</span></dt> <dd>Show and hold the grid (<span class="key">G</span> will remove it again).</dd> <dt><span class="key">G</span> + <span class="key">F</span></dt> <dd>Toggle the grid to the foreground and back. Pressing <span class="key">F</span> while the grid is held also works.</dd> <dt><span class="key">G</span> + <span class="key">J</span></dt> <dd>Jump to the next grid. Pressing <span class="key">J</span> while the grid is held also works.</dd> </dl> <p><em>N.B. A cookie conveniently remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page except in Chrome v4, Safari v4, Firefox v3.6, or more recent versions.</em></p> <h2 id="release-notes">Release Notes</h2> <dl> <dt>v9&#8201;&#8212;&#8201;30 May 2013</dt> <dd>Minor release: Improved example usage to avoid conflicts.</dd> <dt>v8&#8201;&#8212;&#8201;6 Oct 2012</dt> <dd> <ul> <li>Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="http://www.tomarnold.de/">Tom Arnold</a>.</li> <li>Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="http://lynx.io/">Callum Macrae</a>.</li> <li>Fixes to cookie handling. Thanks to <a href="http://loonypandora.co.uk/">James Aitken</a>.</li> <li>Optimisations.</li> </ul> </dd> <dt>v7&#8201;&#8212;&#8201;11 Jun 2011</dt> <dd>Minor release: Updated license references.</dd> <dt>v6&#8201;&#8212;&#8201;10 Jun 2011</dt> <dd>Minor release: Optimisations (thanks to <a href="http://andrewjaswa.com/">Andrew Jaswa</a> for contributions), and now released under an Apache License.</dd> <dt>v5&#8201;&#8212;&#8201;3 Nov 2010</dt> <dd> <ul> <li>Vertical grid lines can now be set using CSS&#8230; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution.</li> <li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li> <li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback.</li> </ul> </dd> <dt>v4&#8201;&#8212;&#8201;29 Mar 2010</dt> <dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd> <dt>v3&#8201;&#8212;&#8201;22 Feb 2010</dt> <dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd> <dt>v2&#8201;&#8212;&#8201;2 Feb 2010</dt> <dd> <ul> <li>Keys are now more easily configured (see top of hashgrid.js).</li> <li>Fixed crash when using with disabled CSS.</li> <li>Renamed the GridOverlay object to hashgrid.</li> </ul> </dd> <dt>v1&#8201;&#8212;&#8201;21 Dec 2009</dt> <dd>First release.</dd> </dl> <h2 id="known-issues">Known Issues</h2> <ul> <li><del>IE 8: Fully functional, but the default <span class="key">ALT</span> + <span class="key">G</span> + <span class="key">ENTER</span> shortcut puts IE into full screen mode. Hit <span class="key">ALT</span> + <span class="key">ENTER</span> to toggle full screen mode off again.</del><ins datetime="2010-02-22"> The default keyboard shortcuts have been changed.</ins></li> <li>IE 6: The grid is always in the foreground.</li> <li>Opera 9/10: Using <span class="key">CTRL</span> or <span class="key">ALT</span> as a modifier key will not work due to different key handling by the browser.</li> </ul> <h2 id="license">License</h2> <p>Copyright 2013-2018 Jon Gibbins</p> <p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br /><br /> <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a></p> <p>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.</p> <p>This essentially means that you&#8217;re free to copy, modify and distribute it for any project so long as you provide clear attribution to the author. <a href="https://dotjay.com/contact">Get in touch</a> if you need a different license.</p> <div id="footer" role="contentinfo"> <p>#grid was built by <a href="https://dotjay.com/">Jon Gibbins</a> and designed by <a href="http://jontangerine.com/">Jon Tan</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p> </div> </div> <!-- Grab latest version of jQuery --> -<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script> +<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <!-- Include the hashgrid script --> <script src="hashgrid.js"></script> <!-- Kick hashgrid into action --> <script> var grid = new hashgrid({ numberOfGrids: 2 }); </script> </body> </html>
dotjay/hashgrid
a2c9f667f1a1279a6f7f2e9715c889b746aa9aa2
Latest date
diff --git a/index.htm b/index.htm index 58e11a0..ff7d393 100644 --- a/index.htm +++ b/index.htm @@ -1,472 +1,472 @@ <!doctype html> <html lang="en-GB"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link rel="shortcut icon" type="image/x-icon" href="favicon.ico"> <title>#grid</title> <style> /* Putting inline rules here so the document can be downloaded with style */ body{ font-size: 1em; line-height: 1.25; font-family: Arial, sans-serif; background: White; color: DimGray; margin: 0; padding: 0 20px; } #content{ font-size: 16px; line-height: 20px; position: relative; } #content{ width: 620px; margin: 0 auto; } #footer{ border-top: 1px dotted DarkGray; padding-top: 19px; } h1, h2{ color: Black; font-weight: normal; } h1{ font-size: 36px; line-height: 40px; margin: 40px 0 20px; padding-bottom: 19px; border-bottom: 1px dotted DarkGray; } h1 em{ font-style: normal; color: DarkGray; font-size: 16px; line-height: 20px; margin: 0 0 20px; } h2, h3{ font-size: 16px; font-weight: 700; line-height: 20px; margin: 0 0 20px; } h3{ font-weight: 300; } a:link, a:visited{ color: Black; text-decoration: none; padding: 0 2px; background-color: WhiteSmoke; border-bottom: 1px solid Gold; } a:focus{ outline: none; } a:focus, a:hover, a:active{ background-color: Khaki; border-bottom: 1px solid GoldenRod; } p, ul{ padding: 0; margin: 0 0 20px; } dl, ol{ padding: 0; margin: 0; } ul{ list-style: circle; } ol li{ margin-bottom: 20px; } dd{ margin: 0 0 20px 0; } del{ text-decoration: line-through; opacity: 0.75; } ins{ text-decoration: none; } code{ font-size: 14px; line-height: 1; } textarea{ font-family: 'Courier New', monospace; font-size: 14px; line-height: 20px; display: block; width: 600px; margin: 0 0 20px; padding: 0 0 0 15px; border: 0; color: Black; background: Gainsboro; border-left: 5px solid DarkGray; } #javascript-code{ height: 280px; } #css-code{ height: 1300px; } .summary em{ font-style: normal; position: absolute; color: DarkGray; right: 0; top: 18px; width: 140px; } .summary em span{ position: absolute; left: -9999px; } #download{ line-height: 60px; padding: 0 40px 0 15px; border-left: 5px solid DarkGray; background: Gainsboro; color: DimGray; } span.key{ color: Black; text-transform: uppercase; } </style> <!-- Set styles --> <style> /** * Grid */ #grid{ /* Dimensions - same width as your grid with gutters */ width: 980px; /* Grid (left-aligned) position: absolute; top: 0; left: 0; */ /* Grid (centered) */ position: absolute; top: 0; left: 50%; margin-left: -490px; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ #grid div.vert{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-right: 19px; } #grid div.vert.first-line{ margin-left: 19px; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ #grid div.horiz{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option in the hashgrid.js file. */ #grid.grid-1 div.vert{ /* Vertical grid line colour for grid 1 */ border-color: darkturquoise; } #grid.grid-2{ /* Adjustments */ padding: 0 160px; width: 660px; } #grid.grid-2 div.vert{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </style> </head> <body> <div id="content" role="main"> <h1>#grid <em>v9</em></h1> -<p class="summary"><em>Sat, 6 Oct 2012<span>:</span></em> #grid (or &#8220;Hashgrid&#8221;) is a little tool that inserts a <a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a> in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit <span class="key">G</span> on your keyboard.</p> +<p class="summary"><em>30 May 2013<span>:</span></em> #grid (or &#8220;Hashgrid&#8221;) is a little tool that inserts a <a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a> in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit <span class="key">G</span> on your keyboard.</p> <h2>Download</h2> <p id="download"><a href="https://github.com/dotjay/hashgrid/downloads">Download #grid</a> from <a href="https://github.com/dotjay/hashgrid">GitHub</a></p> <h2 id="features">Features</h2> <ul> <li>Adaptable for all layout widths and alignments</li> <li>Adaptable for any vertical rhythm value</li> <li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li> <li>Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters</li> </ul> <p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p> <h2 id="installation">Installation</h2> <ol> <li><h3>Copy the <a href="https://github.com/dotjay/hashgrid/blob/v9/hashgrid.js">hashgrid.js</a> script to your project</h3></li> <li><h3>Add the script to your page(s) just inside the <code>&#60;/body&#62;</code> tag</h3> <textarea id="javascript-code" cols="68" rows="14" readonly="readonly"> &#60;!-- Grab latest version of jQuery --&#62; &#60;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"&#62;&#60;/script&#62; &#60;!-- Include the hashgrid script --&#62; &#60;script src="hashgrid.js"&#62;&#60;/script&#62; &#60;!-- Kick hashgrid into action --&#62; &#60;script&#62; var grid = new hashgrid({ numberOfGrids: 2 }); &#60;/script&#62;</textarea></li> <li><h3>Add the CSS to your page(s)</h3> <textarea id="css-code" cols="68" rows="64" readonly="readonly"> /** * Grid */ #grid{ /* Dimensions - same width as your grid with gutters */ width: 980px; /* Grid (left-aligned) position: absolute; top: 0; left: 0; */ /* Grid (centered) */ position: absolute; top: 0; left: 50%; margin-left: -490px; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ #grid div.vert{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-right: 19px; } #grid div.vert.first-line{ margin-left: 19px; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ #grid div.horiz{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option in the hashgrid.js file. */ #grid.grid-1 div.vert{ /* Vertical grid line colour for grid 1 */ border-color: darkturquoise; } #grid.grid-2{ /* Adjustments */ padding: 0 160px; width: 660px; } #grid.grid-2 div.vert{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </textarea></li> <li><h3>Modify #grid to suit your needs</h3> <p>The CSS and JavaScript is annotated to help you.</p></li> </ol> <h2 id="usage">Usage</h2> <p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p> <dl> <dt><span class="key">G</span></dt> <dd>Show the grid until you release.</dd> <dt><span class="key">G</span> + <span class="key">H</span></dt> <dd>Show and hold the grid (<span class="key">G</span> will remove it again).</dd> <dt><span class="key">G</span> + <span class="key">F</span></dt> <dd>Toggle the grid to the foreground and back. Pressing <span class="key">F</span> while the grid is held also works.</dd> <dt><span class="key">G</span> + <span class="key">J</span></dt> <dd>Jump to the next grid. Pressing <span class="key">J</span> while the grid is held also works.</dd> </dl> <p><em>N.B. A cookie conveniently remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page except in Chrome v4, Safari v4, Firefox v3.6, or more recent versions.</em></p> <h2 id="release-notes">Release Notes</h2> <dl> <dt>v9&#8201;&#8212;&#8201;30 May 2013</dt> <dd>Minor release: Improved example usage to avoid conflicts.</dd> <dt>v8&#8201;&#8212;&#8201;6 Oct 2012</dt> <dd> <ul> <li>Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="http://www.tomarnold.de/">Tom Arnold</a>.</li> <li>Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="http://lynx.io/">Callum Macrae</a>.</li> <li>Fixes to cookie handling. Thanks to <a href="http://loonypandora.co.uk/">James Aitken</a>.</li> <li>Optimisations.</li> </ul> </dd> <dt>v7&#8201;&#8212;&#8201;11 Jun 2011</dt> <dd>Minor release: Updated license references.</dd> <dt>v6&#8201;&#8212;&#8201;10 Jun 2011</dt> <dd>Minor release: Optimisations (thanks to <a href="http://andrewjaswa.com/">Andrew Jaswa</a> for contributions), and now released under an Apache License.</dd> <dt>v5&#8201;&#8212;&#8201;3 Nov 2010</dt> <dd> <ul> <li>Vertical grid lines can now be set using CSS&#8230; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution.</li> <li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li> <li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback.</li> </ul> </dd> <dt>v4&#8201;&#8212;&#8201;29 Mar 2010</dt> <dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd> <dt>v3&#8201;&#8212;&#8201;22 Feb 2010</dt> <dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd> <dt>v2&#8201;&#8212;&#8201;2 Feb 2010</dt> <dd> <ul> <li>Keys are now more easily configured (see top of hashgrid.js).</li> <li>Fixed crash when using with disabled CSS.</li> <li>Renamed the GridOverlay object to hashgrid.</li> </ul> </dd> <dt>v1&#8201;&#8212;&#8201;21 Dec 2009</dt> <dd>First release.</dd> </dl> <h2 id="known-issues">Known Issues</h2> <ul> <li><del>IE 8: Fully functional, but the default <span class="key">ALT</span> + <span class="key">G</span> + <span class="key">ENTER</span> shortcut puts IE into full screen mode. Hit <span class="key">ALT</span> + <span class="key">ENTER</span> to toggle full screen mode off again.</del><ins datetime="2010-02-22"> The default keyboard shortcuts have been changed.</ins></li> <li>IE 6: The grid is always in the foreground.</li> <li>Opera 9/10: Using <span class="key">CTRL</span> or <span class="key">ALT</span> as a modifier key will not work due to different key handling by the browser.</li> </ul> <h2 id="license">License</h2> <p>Copyright 2013-2018 Jon Gibbins</p> <p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br /><br /> <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a></p> <p>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.</p> <p>This essentially means that you&#8217;re free to copy, modify and distribute it for any project so long as you provide clear attribution to the author. <a href="https://dotjay.com/contact">Get in touch</a> if you need a different license.</p> <div id="footer" role="contentinfo"> <p>#grid was built by <a href="https://dotjay.com/">Jon Gibbins</a> and designed by <a href="http://jontangerine.com/">Jon Tan</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p> </div> </div> <!-- Grab latest version of jQuery --> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script> <!-- Include the hashgrid script --> <script src="hashgrid.js"></script> <!-- Kick hashgrid into action --> <script> var grid = new hashgrid({ numberOfGrids: 2 }); </script> </body> </html>
dotjay/hashgrid
b886986298d083f4c3e1ed01d16b2d2c6fde9ca5
HTTPS link
diff --git a/README.md b/README.md index 74a467a..30ad3b1 100644 --- a/README.md +++ b/README.md @@ -1,53 +1,53 @@ # #grid # A little tool that inserts a layout grid in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. ## Features ## * Adaptable for all layout widths and alignments * Adaptable for any vertical rhythm value * Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids * Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters ## Install ## Download the latest release from: https://github.com/dotjay/hashgrid/tags Install using [Bower](http://bower.io/): ``` bower install hashgrid#v9 ``` Notes on usage can be found at [dotjay.github.io/hashgrid/#installation](https://dotjay.github.io/hashgrid/#installation). ## Please note ## The latest version of #grid is maintained on Github, and its official web page is: [dotjay.github.io/hashgrid/](https://dotjay.github.io/hashgrid/) It is no longer hosted at hashgrid.com, which is now defunct. ## License ## Copyright 2013-2018 Jon Gibbins Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 + https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -- This essentially means that you're free to copy, modify and distribute it for any project so long as you provide clear attribution to the author. Get in touch if you need a different license. https://dotjay.com/contact
dotjay/hashgrid
9bd543638212b9d2a047bd39bf8aff9e0e31bc56
Clarify official home page
diff --git a/README.md b/README.md index cc3a9f1..74a467a 100644 --- a/README.md +++ b/README.md @@ -1,50 +1,53 @@ # #grid # A little tool that inserts a layout grid in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. ## Features ## * Adaptable for all layout widths and alignments * Adaptable for any vertical rhythm value * Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids * Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters ## Install ## Download the latest release from: https://github.com/dotjay/hashgrid/tags Install using [Bower](http://bower.io/): ``` bower install hashgrid#v9 ``` -Notes on usage can be found at [dotjay.github.io/hashgrid/#installation](http://dotjay.github.io/hashgrid/#installation). +Notes on usage can be found at [dotjay.github.io/hashgrid/#installation](https://dotjay.github.io/hashgrid/#installation). ## Please note ## -The latest version of #grid is maintained here, and is no longer hosted at hashgrid.com, which is now defunct. +The latest version of #grid is maintained on Github, and its official web page is: +[dotjay.github.io/hashgrid/](https://dotjay.github.io/hashgrid/) + +It is no longer hosted at hashgrid.com, which is now defunct. ## License ## Copyright 2013-2018 Jon Gibbins Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -- This essentially means that you're free to copy, modify and distribute it for any project so long as you provide clear attribution to the author. Get in touch if you need a different license. https://dotjay.com/contact
dotjay/hashgrid
43a167c6811e0bc9bb689133e0a296f16e8ef6b8
Note re hashgrid.com being defunct
diff --git a/README.md b/README.md index b9d27fd..cc3a9f1 100644 --- a/README.md +++ b/README.md @@ -1,46 +1,50 @@ # #grid # A little tool that inserts a layout grid in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. ## Features ## * Adaptable for all layout widths and alignments * Adaptable for any vertical rhythm value * Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids * Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters ## Install ## Download the latest release from: https://github.com/dotjay/hashgrid/tags Install using [Bower](http://bower.io/): ``` bower install hashgrid#v9 ``` Notes on usage can be found at [dotjay.github.io/hashgrid/#installation](http://dotjay.github.io/hashgrid/#installation). +## Please note ## + +The latest version of #grid is maintained here, and is no longer hosted at hashgrid.com, which is now defunct. + ## License ## Copyright 2013-2018 Jon Gibbins Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -- This essentially means that you're free to copy, modify and distribute it for any project so long as you provide clear attribution to the author. Get in touch if you need a different license. https://dotjay.com/contact
dotjay/hashgrid
2a10bbe00a142e9c09004d0142fbfe143b012a8d
Correct link
diff --git a/README.md b/README.md index f1ee92e..b9d27fd 100644 --- a/README.md +++ b/README.md @@ -1,46 +1,46 @@ # #grid # A little tool that inserts a layout grid in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. ## Features ## * Adaptable for all layout widths and alignments * Adaptable for any vertical rhythm value * Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids * Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters ## Install ## Download the latest release from: -https://github.com/dotjay/hashgrid/releases +https://github.com/dotjay/hashgrid/tags Install using [Bower](http://bower.io/): ``` bower install hashgrid#v9 ``` Notes on usage can be found at [dotjay.github.io/hashgrid/#installation](http://dotjay.github.io/hashgrid/#installation). ## License ## Copyright 2013-2018 Jon Gibbins Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -- This essentially means that you're free to copy, modify and distribute it for any project so long as you provide clear attribution to the author. Get in touch if you need a different license. https://dotjay.com/contact
dotjay/hashgrid
e439802ee5e31e6db20cb8a9c277c6b756522293
Set theme jekyll-theme-minimal
diff --git a/_config.yml b/_config.yml new file mode 100644 index 0000000..2f7efbe --- /dev/null +++ b/_config.yml @@ -0,0 +1 @@ +theme: jekyll-theme-minimal \ No newline at end of file
dotjay/hashgrid
d7d31ca6d164857ddeca4c18ded08c6a97affccb
homepage url
diff --git a/package.json b/package.json index 0332b86..5e2402b 100644 --- a/package.json +++ b/package.json @@ -1,19 +1,19 @@ { "name": "hashgrid", "version": "0.9.0", "description": "A little tool that inserts a layout grid in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background.", "main": "hashgrid.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/dotjay/hashgrid.git" }, "author": "dotjay", "license": "Apache-2.0", "bugs": { "url": "https://github.com/dotjay/hashgrid/issues" }, - "homepage": "https://github.com/dotjay/hashgrid#readme" + "homepage": "http://hashgrid.com" }
dotjay/hashgrid
55236c3c79800869fbf6b66cf90c727d81acd4a3
original url
diff --git a/package.json b/package.json index 3df58fc..0332b86 100644 --- a/package.json +++ b/package.json @@ -1,19 +1,19 @@ { "name": "hashgrid", "version": "0.9.0", "description": "A little tool that inserts a layout grid in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background.", "main": "hashgrid.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", - "url": "git+https://github.com/ryuran/hashgrid.git" + "url": "git+https://github.com/dotjay/hashgrid.git" }, "author": "dotjay", "license": "Apache-2.0", "bugs": { - "url": "https://github.com/ryuran/hashgrid/issues" + "url": "https://github.com/dotjay/hashgrid/issues" }, - "homepage": "https://github.com/ryuran/hashgrid#readme" + "homepage": "https://github.com/dotjay/hashgrid#readme" }
dotjay/hashgrid
bc5f071f6659e22f78789627d9fa0ce4c9e335ec
add package.json
diff --git a/package.json b/package.json new file mode 100644 index 0000000..3df58fc --- /dev/null +++ b/package.json @@ -0,0 +1,19 @@ +{ + "name": "hashgrid", + "version": "0.9.0", + "description": "A little tool that inserts a layout grid in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background.", + "main": "hashgrid.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ryuran/hashgrid.git" + }, + "author": "dotjay", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/ryuran/hashgrid/issues" + }, + "homepage": "https://github.com/ryuran/hashgrid#readme" +}
dotjay/hashgrid
61adeb7507b8b78540c5c0cff5a46ce88a0ba689
Add jade task and tidy up src folder
diff --git a/Gruntfile.js b/Gruntfile.js index 28bc874..dce362d 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -1,25 +1,25 @@ module.exports = function(grunt) { require("load-grunt-config")(grunt, { data: { - srcDir: "src", - buildDir: "dist", + srcDir: "src/javascripts", + buildDir: "dist/javascripts", tempDir: "temp" } }); grunt.registerMultiTask("removeBlock", function() { - var removalRegEx = new RegExp('(\/\/ ' + this.options()[0] + ' \/\/)(?:[^])*?(\/\/ ' + this.options()[1] + ' \/\/)', 'g'); + var removalRegEx = new RegExp("(\/\/ " + this.options()[0] + " \/\/)(?:[^])*?(\/\/ " + this.options()[1] + " \/\/)", "g"); this.data.files.forEach(function(fileObj){ - var sourceFile = grunt.file.read( fileObj.src ), - removedFile = sourceFile.replace( removalRegEx, '' ), - targetFile = grunt.file.write( fileObj.dest, removedFile ); - - });// for each loop end + var + sourceFile = grunt.file.read( fileObj.src ), + removedFile = sourceFile.replace( removalRegEx, "" ), + targetFile = grunt.file.write( fileObj.dest, removedFile ); + }); }); - grunt.registerTask("build", ["clean:dist", "removeBlock", "uglify", "clean:temp"]); + grunt.registerTask("build", ["clean:dist", "clean:demo", "removeBlock", "uglify", "jade", "clean:temp"]); grunt.registerTask("dev", ["build", "watch"]); grunt.registerTask("default", "build"); }; diff --git a/dist/javascripts/hashgrid.js b/dist/javascripts/hashgrid.js index fc857e5..fe05e9a 100644 --- a/dist/javascripts/hashgrid.js +++ b/dist/javascripts/hashgrid.js @@ -1,374 +1,376 @@ (function(window, document) { var Helper = function() { "use strict"; function copyObjectProperties(target, source) { var properties = Object.getOwnPropertyNames(source); var propertyLength = properties.length; var idx; for (idx = 0; idx < propertyLength; idx++) { target[properties[idx]] = source[properties[idx]]; } } return { getKey: function(event) { var k = false, c = event.keyCode ? event.keyCode : event.which; if (c == 13) k = "enter"; else k = String.fromCharCode(c).toLowerCase(); return k; }, getKeyModifier: function(event, modifierOption) { if (modifierOption === null) return true; var m = true; switch (modifierOption) { case "ctrl": m = event.ctrlKey ? event.ctrlKey : false; break; case "alt": m = event.altKey ? event.altKey : false; break; case "shift": m = event.shiftKey ? event.shiftKey : false; break; } return m; }, mergeObjects: function(mergedObject, obj1, obj2) { if (!mergedObject && !obj1 && !obj2) { return {}; } else if (mergedObject && typeof mergedObject !== "object" || obj1 && typeof obj1 !== "object" || obj2 && typeof obj2 !== "object") { return {}; } if (obj1) { copyObjectProperties(mergedObject, obj1); } if (obj2) { copyObjectProperties(mergedObject, obj2); } return mergedObject; }, forceRepaint: function() { var ss = document.styleSheets[0]; try { ss.addRule(".xxxxxx", "position: relative"); ss.removeRule(ss.rules.length - 1); - } catch (e) {} + } catch (e) { + return; + } } }; }(); var CookieStorage = function() { "use strict"; function CookieStorage() {} CookieStorage.prototype.read = function(cookieLabel) { var cookieCrumb, cookieArray = document.cookie.split(";"), i = 0, cookieCrumbCount = cookieArray.length; cookieLabel = cookieLabel + "="; for (;i < cookieCrumbCount; i++) { cookieCrumb = cookieArray[i]; while (cookieCrumb.charAt(0) === " ") { cookieCrumb = cookieCrumb.substring(1, cookieCrumb.length); } if (cookieCrumb.indexOf(cookieLabel) === 0) { return JSON.parse(cookieCrumb.substring(cookieLabel.length, cookieCrumb.length)); } } return null; }; CookieStorage.prototype.write = function(cookieLabel, cookieValue, expirationDay) { var date, cookieExpires = "", toBeWritten = ""; if (expirationDay) { date = new Date(); date.setTime(date.getTime() + expirationDay * 24 * 60 * 60 * 1e3); cookieExpires = "; expires=" + date.toGMTString(); } toBeWritten = cookieLabel + "=" + JSON.stringify(cookieValue) + cookieExpires + "; path=/"; document.cookie = toBeWritten; return toBeWritten; }; CookieStorage.prototype.remove = function(cookieLabel) { var removedCookieValue = this.read(cookieLabel); if (removedCookieValue) { this.write(cookieLabel, "", -1); return removedCookieValue; } else { return null; } }; return CookieStorage; }(); var SessionStorage = function() { "use strict"; function SessionStorage() { this.storage = window.sessionStorage; } - SessionStorage.prototype.read = function(dataLabel) { - var dataValue = this.storage.getItem(dataLabel); - if (dataValue) { - return JSON.parse(dataValue); - } else { - return null; - } - }; - SessionStorage.prototype.write = function(dataLabel, dataValue) { - this.storage.setItem(dataLabel, JSON.stringify(dataValue)); - return dataValue; - }; - SessionStorage.prototype.remove = function(dataLabel) { - var removedDataValue = this.read(dataLabel); - if (removedDataValue) { - this.storage.removeItem(dataLabel); - return removedDataValue; - } else { - return null; - } - }; return SessionStorage; }(); - var Storage = function() { + SessionStorage.prototype.read = function(dataLabel) { + var dataValue = this.storage.getItem(dataLabel); + if (dataValue) { + return JSON.parse(dataValue); + } else { + return null; + } + }; + SessionStorage.prototype.write = function(dataLabel, dataValue) { + this.storage.setItem(dataLabel, JSON.stringify(dataValue)); + return dataValue; + }; + SessionStorage.prototype.remove = function(dataLabel) { + var removedDataValue = this.read(dataLabel); + if (removedDataValue) { + this.storage.removeItem(dataLabel); + return removedDataValue; + } else { + return null; + } + }; + var SimpleStorage = function() { "use strict"; - function Storage() { + function SimpleStorage() { if (this.hasSessionStorage()) { return new SessionStorage(); } else { return new CookieStorage(); } } - Storage.prototype.hasSessionStorage = function() { - try { - var storage = window.sessionStorage, someData = "some value"; - storage.setItem(someData, someData); - storage.removeItem(someData); - return true; - } catch (e) { - return false; - } - }; - return Storage; + return SimpleStorage; }(); + SimpleStorage.prototype.hasSessionStorage = function() { + try { + var storage = window.sessionStorage, someData = "some value"; + storage.setItem(someData, someData); + storage.removeItem(someData); + return true; + } catch (e) { + return false; + } + }; var Hashgrid = function() { "use strict"; - var storage = new Storage(), fillGrid, boundKeydownHandler, keydownHandler, boundKeyupHandler, keyupHandler, createStorageData; + var storage = new SimpleStorage(), fillGrid, boundKeydownHandler, keydownHandler, boundKeyupHandler, keyupHandler, createStorageData; function Hashgrid(customOptions) { var defaultOptions = { id: "hashgrid", modifierKey: null, showGridKey: "g", holdGridKey: "h", foregroundKey: "f", jumpGridsKey: "j", numberOfGrids: 1, classPrefix: "hashgrid", storagePrefix: "hashgrid" }, privateOptions = { overlayZBG: "-1", overlayZFG: "9999" }; this.options = Helper.mergeObjects(defaultOptions, customOptions, privateOptions); this.state = { overlayHold: false, overlayOn: false, overlayZIndex: "B", isKeyDown: {}, gridNumber: 1 }; this.init(); } Hashgrid.prototype.init = function() { var storageData; this.overlay = document.createElement("div"); this.overlay.id = this.options.id; this.overlay.classList.add(this.options.classPrefix + this.state.gridNumber); this.overlay.style.display = "none"; this.overlay.style.pointerEvents = "none"; this.overlay.style.height = document.body.scrollHeight + "px"; if (this.overlay.style.zIndex === "auto") { this.overlay.style.zIndex = this.overlayZBackground; } document.body.insertBefore(this.overlay, document.body.firstChild); boundKeydownHandler = keydownHandler.bind(this); boundKeyupHandler = keyupHandler.bind(this); if (document.addEventListener) { document.addEventListener("keydown", boundKeydownHandler, false); document.addEventListener("keyup", boundKeyupHandler, false); } else if (document.attachEvent) { document.attachEvent("onkeydown", boundKeydownHandler); document.attachEvent("onkeyup", boundKeyupHandler); } fillGrid.call(this); storageData = storage.read(this.options.storagePrefix + this.options.id); if (storageData) { if (storageData.gridNumber) { this.overlay.classList.remove(this.options.classPrefix + this.state.gridNumber); this.overlay.classList.add(this.options.classPrefix + storageData.gridNumber); this.state.gridNumber = storageData.gridNumber; } if (storageData.overlayHold) { this.overlay.style.display = "block"; this.state.overlayOn = true; this.state.overlayHold = true; } if (storageData.overlayZIndex) { if (storageData.overlayZIndex === "B") { this.overlay.style.zIndex = this.options.overlayZBG; } else if (storageData.overlayZIndex === "F") { this.overlay.style.zIndex = this.options.overlayZFG; } this.state.overlayZIndex = storageData.overlayZIndex; } } }; Hashgrid.prototype.showOverlay = function() { this.overlay.style.display = "block"; this.state.overlayOn = true; }; Hashgrid.prototype.hideOverlay = function() { this.overlay.style.display = "none"; this.state.overlayOn = false; }; Hashgrid.prototype.destroy = function() { this.overlay.remove(); storage.remove(this.options.storagePrefix + this.options.id); if (document.removeEventListener) { document.removeEventListener("keydown", boundKeydownHandler); document.removeEventListener("keyup", boundKeyupHandler); } else if (document.detachevent) { document.detachEvent("onkeydown", boundKeydownHandler); document.detachEvent("onkeyup", boundKeyupHandler); } }; fillGrid = function() { var columnContainer = document.createElement("div"), column = document.createElement("div"), columnCount = 0, columnWidth, docFragment = document.createDocumentFragment(), options = this.options, overlay = this.overlay, overlayHeight, overlayWidth, rowContainer = document.createElement("div"), row = document.createElement("div"), rowCount = 0, rowHeight; rowContainer.classList.add(options.id + "-row-container"); columnContainer.classList.add(options.id + "-column-container"); overlay.appendChild(rowContainer); overlay.appendChild(columnContainer); row.classList.add(options.id + "__row"); column.classList.add(options.id + "__column"); rowContainer.appendChild(row); columnContainer.appendChild(column); overlay.style.display = "block"; overlay.top = "-9999px"; overlayHeight = overlay.scrollHeight; overlayWidth = overlay.scrollWidth; rowHeight = row.getBoundingClientRect().height; columnWidth = column.clientWidth; overlay.style.display = "none"; overlay.top = "0"; if (!rowHeight && !columnWidth) { return false; } if (rowHeight) { rowCount = Math.floor(overlayHeight / rowHeight) - 1; while (rowCount--) { row = document.createElement("div"); row.classList.add(options.id + "__row"); docFragment.appendChild(row); } rowContainer.appendChild(docFragment); } else { rowContainer.remove(row); } if (columnWidth) { columnCount = Math.floor(overlayWidth / columnWidth) - 2; while (columnCount--) { column = document.createElement("div"); column.classList.add(options.id + "__column"); docFragment.appendChild(column); } columnContainer.appendChild(docFragment); } else { columnContainer.remove(column); } }; keydownHandler = function(event) { var k, m, options = this.options, state = this.state, source = event.target.tagName.toLowerCase(); if (source == "input" || source == "textarea" || source == "select") { return true; } m = Helper.getKeyModifier(event, options.modifierKey); if (!m) { return true; } k = Helper.getKey(event); if (!k) { return true; } if (state.isKeyDown[k]) { return true; } state.isKeyDown[k] = true; switch (k) { case options.showGridKey: if (!state.overlayOn) { this.showOverlay(); state.overlayOn = true; } else if (state.overlayHold) { this.hideOverlay(); state.overlayOn = false; state.overlayHold = false; storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; case options.holdGridKey: if (state.overlayOn && !state.overlayHold) { state.overlayHold = true; storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; case options.foregroundKey: if (state.overlayOn) { if (this.overlay.style.zIndex === options.overlayZFG) { this.overlay.style.zIndex = options.overlayZBG; state.overlayZIndex = "B"; } else { this.overlay.style.zIndex = options.overlayZFG; state.overlayZIndex = "F"; } storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; case options.jumpGridsKey: if (state.overlayOn && options.numberOfGrids > 1) { this.overlay.classList.remove(options.classPrefix + state.gridNumber); state.gridNumber += 1; if (state.gridNumber > options.numberOfGrids) { state.gridNumber = 1; } this.overlay.classList.add(options.classPrefix + state.gridNumber); this.showOverlay(); if (/webkit/.test(navigator.userAgent.toLowerCase())) { Helper.forceRepaint(); } storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; } return true; }; keyupHandler = function(event) { var k, m = Helper.getKeyModifier(event), options = this.options, state = this.state; if (!m) { return true; } k = Helper.getKey(event); delete state.isKeyDown[k]; if (k && k == options.showGridKey && !state.overlayHold) { this.hideOverlay(); state.overlayOn = false; } return true; }; createStorageData = function() { var state = this.state; return { gridNumber: state.gridNumber, overlayHold: state.overlayHold, overlayZIndex: state.overlayZIndex }; }; return Hashgrid; }(); window.Hashgrid = Hashgrid; })(window, document); \ No newline at end of file diff --git a/dist/javascripts/hashgrid.min.js b/dist/javascripts/hashgrid.min.js index 2eebfc3..b3b296d 100644 --- a/dist/javascripts/hashgrid.min.js +++ b/dist/javascripts/hashgrid.min.js @@ -1 +1 @@ -!function(a,b){var c=function(){"use strict";function a(a,b){var c,d=Object.getOwnPropertyNames(b),e=d.length;for(c=0;e>c;c++)a[d[c]]=b[d[c]]}return{getKey:function(a){var b=!1,c=a.keyCode?a.keyCode:a.which;return b=13==c?"enter":String.fromCharCode(c).toLowerCase()},getKeyModifier:function(a,b){if(null===b)return!0;var c=!0;switch(b){case"ctrl":c=a.ctrlKey?a.ctrlKey:!1;break;case"alt":c=a.altKey?a.altKey:!1;break;case"shift":c=a.shiftKey?a.shiftKey:!1}return c},mergeObjects:function(b,c,d){return b||c||d?b&&"object"!=typeof b||c&&"object"!=typeof c||d&&"object"!=typeof d?{}:(c&&a(b,c),d&&a(b,d),b):{}},forceRepaint:function(){var a=b.styleSheets[0];try{a.addRule(".xxxxxx","position: relative"),a.removeRule(a.rules.length-1)}catch(c){}}}}(),d=function(){"use strict";function a(){}return a.prototype.read=function(a){var c,d=b.cookie.split(";"),e=0,f=d.length;for(a+="=";f>e;e++){for(c=d[e];" "===c.charAt(0);)c=c.substring(1,c.length);if(0===c.indexOf(a))return JSON.parse(c.substring(a.length,c.length))}return null},a.prototype.write=function(a,c,d){var e,f="",g="";return d&&(e=new Date,e.setTime(e.getTime()+24*d*60*60*1e3),f="; expires="+e.toGMTString()),g=a+"="+JSON.stringify(c)+f+"; path=/",b.cookie=g,g},a.prototype.remove=function(a){var b=this.read(a);return b?(this.write(a,"",-1),b):null},a}(),e=function(){"use strict";function b(){this.storage=a.sessionStorage}return b.prototype.read=function(a){var b=this.storage.getItem(a);return b?JSON.parse(b):null},b.prototype.write=function(a,b){return this.storage.setItem(a,JSON.stringify(b)),b},b.prototype.remove=function(a){var b=this.read(a);return b?(this.storage.removeItem(a),b):null},b}(),f=function(){"use strict";function b(){return this.hasSessionStorage()?new e:new d}return b.prototype.hasSessionStorage=function(){try{var b=a.sessionStorage,c="some value";return b.setItem(c,c),b.removeItem(c),!0}catch(d){return!1}},b}(),g=function(){"use strict";function a(a){var b={id:"hashgrid",modifierKey:null,showGridKey:"g",holdGridKey:"h",foregroundKey:"f",jumpGridsKey:"j",numberOfGrids:1,classPrefix:"hashgrid",storagePrefix:"hashgrid"},d={overlayZBG:"-1",overlayZFG:"9999"};this.options=c.mergeObjects(b,a,d),this.state={overlayHold:!1,overlayOn:!1,overlayZIndex:"B",isKeyDown:{},gridNumber:1},this.init()}var d,e,g,h,i,j,k=new f;return a.prototype.init=function(){var a;this.overlay=b.createElement("div"),this.overlay.id=this.options.id,this.overlay.classList.add(this.options.classPrefix+this.state.gridNumber),this.overlay.style.display="none",this.overlay.style.pointerEvents="none",this.overlay.style.height=b.body.scrollHeight+"px","auto"===this.overlay.style.zIndex&&(this.overlay.style.zIndex=this.overlayZBackground),b.body.insertBefore(this.overlay,b.body.firstChild),e=g.bind(this),h=i.bind(this),b.addEventListener?(b.addEventListener("keydown",e,!1),b.addEventListener("keyup",h,!1)):b.attachEvent&&(b.attachEvent("onkeydown",e),b.attachEvent("onkeyup",h)),d.call(this),a=k.read(this.options.storagePrefix+this.options.id),a&&(a.gridNumber&&(this.overlay.classList.remove(this.options.classPrefix+this.state.gridNumber),this.overlay.classList.add(this.options.classPrefix+a.gridNumber),this.state.gridNumber=a.gridNumber),a.overlayHold&&(this.overlay.style.display="block",this.state.overlayOn=!0,this.state.overlayHold=!0),a.overlayZIndex&&("B"===a.overlayZIndex?this.overlay.style.zIndex=this.options.overlayZBG:"F"===a.overlayZIndex&&(this.overlay.style.zIndex=this.options.overlayZFG),this.state.overlayZIndex=a.overlayZIndex))},a.prototype.showOverlay=function(){this.overlay.style.display="block",this.state.overlayOn=!0},a.prototype.hideOverlay=function(){this.overlay.style.display="none",this.state.overlayOn=!1},a.prototype.destroy=function(){this.overlay.remove(),k.remove(this.options.storagePrefix+this.options.id),b.removeEventListener?(b.removeEventListener("keydown",e),b.removeEventListener("keyup",h)):b.detachevent&&(b.detachEvent("onkeydown",e),b.detachEvent("onkeyup",h))},d=function(){var a,c,d,e,f=b.createElement("div"),g=b.createElement("div"),h=0,i=b.createDocumentFragment(),j=this.options,k=this.overlay,l=b.createElement("div"),m=b.createElement("div"),n=0;if(l.classList.add(j.id+"-row-container"),f.classList.add(j.id+"-column-container"),k.appendChild(l),k.appendChild(f),m.classList.add(j.id+"__row"),g.classList.add(j.id+"__column"),l.appendChild(m),f.appendChild(g),k.style.display="block",k.top="-9999px",c=k.scrollHeight,d=k.scrollWidth,e=m.getBoundingClientRect().height,a=g.clientWidth,k.style.display="none",k.top="0",!e&&!a)return!1;if(e){for(n=Math.floor(c/e)-1;n--;)m=b.createElement("div"),m.classList.add(j.id+"__row"),i.appendChild(m);l.appendChild(i)}else l.remove(m);if(a){for(h=Math.floor(d/a)-2;h--;)g=b.createElement("div"),g.classList.add(j.id+"__column"),i.appendChild(g);f.appendChild(i)}else f.remove(g)},g=function(a){var b,d,e=this.options,f=this.state,g=a.target.tagName.toLowerCase();if("input"==g||"textarea"==g||"select"==g)return!0;if(d=c.getKeyModifier(a,e.modifierKey),!d)return!0;if(b=c.getKey(a),!b)return!0;if(f.isKeyDown[b])return!0;switch(f.isKeyDown[b]=!0,b){case e.showGridKey:f.overlayOn?f.overlayHold&&(this.hideOverlay(),f.overlayOn=!1,f.overlayHold=!1,k.write(e.storagePrefix+e.id,j.call(this))):(this.showOverlay(),f.overlayOn=!0);break;case e.holdGridKey:f.overlayOn&&!f.overlayHold&&(f.overlayHold=!0,k.write(e.storagePrefix+e.id,j.call(this)));break;case e.foregroundKey:f.overlayOn&&(this.overlay.style.zIndex===e.overlayZFG?(this.overlay.style.zIndex=e.overlayZBG,f.overlayZIndex="B"):(this.overlay.style.zIndex=e.overlayZFG,f.overlayZIndex="F"),k.write(e.storagePrefix+e.id,j.call(this)));break;case e.jumpGridsKey:f.overlayOn&&e.numberOfGrids>1&&(this.overlay.classList.remove(e.classPrefix+f.gridNumber),f.gridNumber+=1,f.gridNumber>e.numberOfGrids&&(f.gridNumber=1),this.overlay.classList.add(e.classPrefix+f.gridNumber),this.showOverlay(),/webkit/.test(navigator.userAgent.toLowerCase())&&c.forceRepaint(),k.write(e.storagePrefix+e.id,j.call(this)))}return!0},i=function(a){var b,d=c.getKeyModifier(a),e=this.options,f=this.state;return d?(b=c.getKey(a),delete f.isKeyDown[b],b&&b==e.showGridKey&&!f.overlayHold&&(this.hideOverlay(),f.overlayOn=!1),!0):!0},j=function(){var a=this.state;return{gridNumber:a.gridNumber,overlayHold:a.overlayHold,overlayZIndex:a.overlayZIndex}},a}();a.Hashgrid=g}(window,document); \ No newline at end of file +!function(a,b){var c=function(){"use strict";function a(a,b){var c,d=Object.getOwnPropertyNames(b),e=d.length;for(c=0;e>c;c++)a[d[c]]=b[d[c]]}return{getKey:function(a){var b=!1,c=a.keyCode?a.keyCode:a.which;return b=13==c?"enter":String.fromCharCode(c).toLowerCase()},getKeyModifier:function(a,b){if(null===b)return!0;var c=!0;switch(b){case"ctrl":c=a.ctrlKey?a.ctrlKey:!1;break;case"alt":c=a.altKey?a.altKey:!1;break;case"shift":c=a.shiftKey?a.shiftKey:!1}return c},mergeObjects:function(b,c,d){return b||c||d?b&&"object"!=typeof b||c&&"object"!=typeof c||d&&"object"!=typeof d?{}:(c&&a(b,c),d&&a(b,d),b):{}},forceRepaint:function(){var a=b.styleSheets[0];try{a.addRule(".xxxxxx","position: relative"),a.removeRule(a.rules.length-1)}catch(c){return}}}}(),d=function(){"use strict";function a(){}return a.prototype.read=function(a){var c,d=b.cookie.split(";"),e=0,f=d.length;for(a+="=";f>e;e++){for(c=d[e];" "===c.charAt(0);)c=c.substring(1,c.length);if(0===c.indexOf(a))return JSON.parse(c.substring(a.length,c.length))}return null},a.prototype.write=function(a,c,d){var e,f="",g="";return d&&(e=new Date,e.setTime(e.getTime()+24*d*60*60*1e3),f="; expires="+e.toGMTString()),g=a+"="+JSON.stringify(c)+f+"; path=/",b.cookie=g,g},a.prototype.remove=function(a){var b=this.read(a);return b?(this.write(a,"",-1),b):null},a}(),e=function(){"use strict";function b(){this.storage=a.sessionStorage}return b}();e.prototype.read=function(a){var b=this.storage.getItem(a);return b?JSON.parse(b):null},e.prototype.write=function(a,b){return this.storage.setItem(a,JSON.stringify(b)),b},e.prototype.remove=function(a){var b=this.read(a);return b?(this.storage.removeItem(a),b):null};var f=function(){"use strict";function a(){return this.hasSessionStorage()?new e:new d}return a}();f.prototype.hasSessionStorage=function(){try{var b=a.sessionStorage,c="some value";return b.setItem(c,c),b.removeItem(c),!0}catch(d){return!1}};var g=function(){"use strict";function a(a){var b={id:"hashgrid",modifierKey:null,showGridKey:"g",holdGridKey:"h",foregroundKey:"f",jumpGridsKey:"j",numberOfGrids:1,classPrefix:"hashgrid",storagePrefix:"hashgrid"},d={overlayZBG:"-1",overlayZFG:"9999"};this.options=c.mergeObjects(b,a,d),this.state={overlayHold:!1,overlayOn:!1,overlayZIndex:"B",isKeyDown:{},gridNumber:1},this.init()}var d,e,g,h,i,j,k=new f;return a.prototype.init=function(){var a;this.overlay=b.createElement("div"),this.overlay.id=this.options.id,this.overlay.classList.add(this.options.classPrefix+this.state.gridNumber),this.overlay.style.display="none",this.overlay.style.pointerEvents="none",this.overlay.style.height=b.body.scrollHeight+"px","auto"===this.overlay.style.zIndex&&(this.overlay.style.zIndex=this.overlayZBackground),b.body.insertBefore(this.overlay,b.body.firstChild),e=g.bind(this),h=i.bind(this),b.addEventListener?(b.addEventListener("keydown",e,!1),b.addEventListener("keyup",h,!1)):b.attachEvent&&(b.attachEvent("onkeydown",e),b.attachEvent("onkeyup",h)),d.call(this),a=k.read(this.options.storagePrefix+this.options.id),a&&(a.gridNumber&&(this.overlay.classList.remove(this.options.classPrefix+this.state.gridNumber),this.overlay.classList.add(this.options.classPrefix+a.gridNumber),this.state.gridNumber=a.gridNumber),a.overlayHold&&(this.overlay.style.display="block",this.state.overlayOn=!0,this.state.overlayHold=!0),a.overlayZIndex&&("B"===a.overlayZIndex?this.overlay.style.zIndex=this.options.overlayZBG:"F"===a.overlayZIndex&&(this.overlay.style.zIndex=this.options.overlayZFG),this.state.overlayZIndex=a.overlayZIndex))},a.prototype.showOverlay=function(){this.overlay.style.display="block",this.state.overlayOn=!0},a.prototype.hideOverlay=function(){this.overlay.style.display="none",this.state.overlayOn=!1},a.prototype.destroy=function(){this.overlay.remove(),k.remove(this.options.storagePrefix+this.options.id),b.removeEventListener?(b.removeEventListener("keydown",e),b.removeEventListener("keyup",h)):b.detachevent&&(b.detachEvent("onkeydown",e),b.detachEvent("onkeyup",h))},d=function(){var a,c,d,e,f=b.createElement("div"),g=b.createElement("div"),h=0,i=b.createDocumentFragment(),j=this.options,k=this.overlay,l=b.createElement("div"),m=b.createElement("div"),n=0;if(l.classList.add(j.id+"-row-container"),f.classList.add(j.id+"-column-container"),k.appendChild(l),k.appendChild(f),m.classList.add(j.id+"__row"),g.classList.add(j.id+"__column"),l.appendChild(m),f.appendChild(g),k.style.display="block",k.top="-9999px",c=k.scrollHeight,d=k.scrollWidth,e=m.getBoundingClientRect().height,a=g.clientWidth,k.style.display="none",k.top="0",!e&&!a)return!1;if(e){for(n=Math.floor(c/e)-1;n--;)m=b.createElement("div"),m.classList.add(j.id+"__row"),i.appendChild(m);l.appendChild(i)}else l.remove(m);if(a){for(h=Math.floor(d/a)-2;h--;)g=b.createElement("div"),g.classList.add(j.id+"__column"),i.appendChild(g);f.appendChild(i)}else f.remove(g)},g=function(a){var b,d,e=this.options,f=this.state,g=a.target.tagName.toLowerCase();if("input"==g||"textarea"==g||"select"==g)return!0;if(d=c.getKeyModifier(a,e.modifierKey),!d)return!0;if(b=c.getKey(a),!b)return!0;if(f.isKeyDown[b])return!0;switch(f.isKeyDown[b]=!0,b){case e.showGridKey:f.overlayOn?f.overlayHold&&(this.hideOverlay(),f.overlayOn=!1,f.overlayHold=!1,k.write(e.storagePrefix+e.id,j.call(this))):(this.showOverlay(),f.overlayOn=!0);break;case e.holdGridKey:f.overlayOn&&!f.overlayHold&&(f.overlayHold=!0,k.write(e.storagePrefix+e.id,j.call(this)));break;case e.foregroundKey:f.overlayOn&&(this.overlay.style.zIndex===e.overlayZFG?(this.overlay.style.zIndex=e.overlayZBG,f.overlayZIndex="B"):(this.overlay.style.zIndex=e.overlayZFG,f.overlayZIndex="F"),k.write(e.storagePrefix+e.id,j.call(this)));break;case e.jumpGridsKey:f.overlayOn&&e.numberOfGrids>1&&(this.overlay.classList.remove(e.classPrefix+f.gridNumber),f.gridNumber+=1,f.gridNumber>e.numberOfGrids&&(f.gridNumber=1),this.overlay.classList.add(e.classPrefix+f.gridNumber),this.showOverlay(),/webkit/.test(navigator.userAgent.toLowerCase())&&c.forceRepaint(),k.write(e.storagePrefix+e.id,j.call(this)))}return!0},i=function(a){var b,d=c.getKeyModifier(a),e=this.options,f=this.state;return d?(b=c.getKey(a),delete f.isKeyDown[b],b&&b==e.showGridKey&&!f.overlayHold&&(this.hideOverlay(),f.overlayOn=!1),!0):!0},j=function(){var a=this.state;return{gridNumber:a.gridNumber,overlayHold:a.overlayHold,overlayZIndex:a.overlayZIndex}},a}();a.Hashgrid=g}(window,document); \ No newline at end of file diff --git a/grunt/clean.js b/grunt/clean.js index 991ed3b..826ee44 100644 --- a/grunt/clean.js +++ b/grunt/clean.js @@ -1,8 +1,11 @@ module.exports = { dist: { src: ["<%= buildDir %>"] }, temp: { src: ["<%= tempDir %>"] + }, + demo: { + src: ["index.html"] } }; diff --git a/grunt/jade.js b/grunt/jade.js new file mode 100644 index 0000000..dde8a99 --- /dev/null +++ b/grunt/jade.js @@ -0,0 +1,7 @@ +module.exports = { + demo: { + files: { + "index.html": "src/index.jade" + } + } +}; diff --git a/grunt/uglify.js b/grunt/uglify.js index bddd029..38805c7 100644 --- a/grunt/uglify.js +++ b/grunt/uglify.js @@ -1,39 +1,39 @@ var srcFiles = [ "<%= tempDir %>/helper.js", "<%= tempDir %>/cookieStorage.js", "<%= tempDir %>/sessionStorage.js", "<%= tempDir %>/storage.js", "<%= tempDir %>/hashgrid.js" ]; module.exports = { options: { enclose: { "window": "window", "document": "document" - }, + } }, normal: { options: { mangle: false, compress: false, beautify: true }, files: { - "<%= buildDir %>/javascripts/hashgrid.js": srcFiles + "<%= buildDir %>/hashgrid.js": srcFiles } }, min: { options: { mangle: true, compress: true }, files: { - "<%= buildDir %>/javascripts/hashgrid.min.js": srcFiles + "<%= buildDir %>/hashgrid.min.js": srcFiles } } }; diff --git a/grunt/watch.js b/grunt/watch.js index a95286d..1888035 100644 --- a/grunt/watch.js +++ b/grunt/watch.js @@ -1,11 +1,10 @@ module.exports = { javascripts: { - files: [ - "<%= srcDir %>/**/*.js" - ], - - tasks: [ - "build" - ] + files: ["<%= srcDir %>/**/*.js"], + tasks: ["build"] + }, + demo: { + files: ["src/index.jade"], + tasks: ["build"] } }; diff --git a/index.htm b/index.htm deleted file mode 100644 index bd920f4..0000000 --- a/index.htm +++ /dev/null @@ -1,459 +0,0 @@ -<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> -<html lang="en"> - -<head> -<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> -<title>#grid</title> - -<style type="text/css"> - -/* Putting inline rules here so the document can be downloaded with style */ - -body{ -font-size: 1em; -line-height: 1.25; -font-family: Arial, sans-serif; -background: White; -color: DimGray; -margin: 0; -} -#content{ -font-size: 16px; -line-height: 20px; -position: relative; -} -#content{ -width: 620px; -margin: 0 auto; -} -#footer{ -border-top: 1px dotted DarkGray; -padding-top: 19px; -} -h1, h2{ -color: Black; -font-weight: normal; -} -h1{ -font-size: 36px; -line-height: 40px; -margin: 40px 0 20px; -padding-bottom: 19px; -border-bottom: 1px dotted DarkGray; -} -h1 em{ -font-style: normal; -color: DarkGray; -font-size: 16px; -line-height: 20px; -margin: 0 0 20px; -} -h2, h3{ -font-size: 16px; -font-weight: 700; -line-height: 20px; -margin: 0 0 20px; -} -h3{ -font-weight: 300; -} -a:link, -a:visited{ -color: Black; -text-decoration: none; -padding: 0 2px; -background-color: WhiteSmoke; -border-bottom: 1px solid Gold; -} -a:focus{ -outline: none; -} -a:focus, -a:hover, -a:active{ -background-color: Khaki; -border-bottom: 1px solid GoldenRod; -} -p, ul{ -padding: 0; -margin: 0 0 20px; -} -dl, ol{ -padding: 0; -margin: 0; -} -ul{ -list-style: circle; -} -ol li{ -margin-bottom: 20px; -} -dd{ -margin: 0 0 20px 0; -} -del{ -text-decoration: line-through; -opacity: 0.75; -} -ins{ -text-decoration: none; -} -code{ -font-size: 14px; -line-height: 1; -} -textarea{ -font-family: 'Courier New', monospace; -font-size: 14px; -line-height: 20px; -display: block; -width: 600px; -margin: 0 0 20px; -padding: 0 0 0 15px; -border: 0; -color: Black; -background: Gainsboro; -border-left: 5px solid DarkGray; -} -#javascript-code{ -height: 320px; -} -#css-code{ -height: 1580px; -} -.summary em{ -font-style: normal; -position: absolute; -color: DarkGray; -right: 0; -top: 18px; -width: 140px; -} -.summary em span{ -position: absolute; -left: -9999px; -} -#download{ -line-height: 60px; -padding: 0 40px 0 15px; -border-left: 5px solid DarkGray; -background: Gainsboro; -color: DimGray; -} -span.key{ -color: Black; -text-transform: uppercase; -} -</style> - -<!-- Set styles --> -<style type="text/css"> - -/** - * Grid - */ -#hashgrid{ - /* Spreads the whole page by default, adjust to match your container */ - /*width: 100%;*/ - width: 980px; - position: absolute; - height: 100%; - top: 0; - left: 50%; - margin-left: -490px; - overflow: hidden; -} - -.hashgrid-column-container { - position: absolute; - height: 100%; - width: 100%; - top: 0; - left: 0; -} - -/** - * Vertical grid lines - * - * Set the column width taking the borders into consideration, - * and use margins to set column gutters. - */ -.hashgrid__column{ - width: 139px; - border: solid darkturquoise; - border-width: 0 1px; - margin-left: 19px; - height: 100%; - float: left; -} - -/** - * Horizontal grid lines, defined by your base line height - * - * Remember, the CSS properties that define the box model: - * visible height = height + borders + margins + padding - */ -.hashgrid__row{ - /* 20px line height */ - height: 19px; - border-bottom: 1px dotted darkgray; - margin: 0; - padding: 0; -} - -/** - * Classes for multiple grids - * - * When using more than one grid, remember to set the numberOfGrids - * option when instantiating hashgrid. - * e.g. - * - * var hg = new Hashgrid({ - * numberOfGrids: 2 - * }); - */ -#hashgrid.hashgrid2, -#hashgrid.hashgrid2 .hashgrid-column-container{ - /* Container width adjustments */ - padding: 0 160px; - width: 660px; -} - -#hashgrid.hashgrid2 .hashgrid__column{ - /* Vertical grid line colour for grid 2 */ - border-color: crimson; -} - - - - -</style> - -</head> - -<body> - -<div id="content" role="main"> - -<h1>#grid <em>v10</em></h1> - -<p class="summary"><em>Mon, 30 Nov 2015<span>:</span></em> This is a little tool we created for our <a href="http://analog.coop/">Analog&#160;holding&#160;page</a>. It inserts a <a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a> in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit <span class="key">g</span> on your keyboard.</p> - -<h2>Download</h2> -<p id="download"><a href="https://github.com/dotjay/hashgrid/downloads">Download #grid</a> from <a href="https://github.com/dotjay/hashgrid">GitHub</a></p> - -<h2 id="features">Features</h2> -<ul> -<li>Adaptable for all layout widths and alignments</li> -<li>Adaptable for any vertical rhythm value</li> -<li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li> -<li>Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters</li> -</ul> -<p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p> - -<h2 id="installation">Installation</h2> -<ol> -<li><h3>Copy the <a href="https://github.com/dotjay/hashgrid/blob/v9/hashgrid.js">hashgrid.js</a> script to your project</h3></li> -<li><h3>Add this script to your page(s) just before the closing <code>&#60;/body&#62;</code> tag</h3> -<textarea id="javascript-code" cols="68" rows="15" readonly="readonly"> - -&#60;!-- Include the hashgrid script --&#62; -&#60;script type="text/javascript" src="hashgrid.js"&#62;&#60;/script&#62; - -&#60;!-- Kick hashgrid into action --&#62; -&#60;script type="text/javascript"&#62; -var grid = new Hashgrid({ numberOfGrids: 2 }); -&#60;/script&#62; - -&#60;!-- Note: Use window onload if your css is not inlined --&#62; -&#60;script type="text/javascript"&#62; -window.addEventListener("load", function(event) { - var grid = new Hashgrid({ numberOfGrids: 2 }); -}); -&#60;/script&#62;</textarea></li> -<li><h3>Add the CSS to your page(s)</h3> -<textarea id="css-code" cols="68" rows="64" readonly="readonly"> - -/** - * Grid - */ -#hashgrid{ - /* - * Spreads the whole page by default - * Adjust to match your container - */ - /*width: 100%;*/ - width: 980px; - position: absolute; - height: 100%; - top: 0; - left: 50%; - margin-left: -490px; - overflow: hidden; -} - -.hashgrid-column-container { - position: absolute; - height: 100%; - width: 100%; - top: 0; - left: 0; -} - -/** - * Vertical grid lines - * - * Set the column width taking the borders into consideration, - * and use margins to set column gutters. - */ -.hashgrid__column{ - width: 139px; - border: solid darkturquoise; - border-width: 0 1px; - margin-left: 19px; - height: 100%; - float: left; -} - -/** - * Horizontal grid lines, defined by your base line height - * - * Remember, the CSS properties that define the box model: - * visible height = height + borders + margins + padding - */ -.hashgrid__row{ - /* 20px line height */ - height: 19px; - border-bottom: 1px dotted darkgray; - margin: 0; - padding: 0; -} - -/** - * Classes for multiple grids - * - * When using more than one grid, remember to set the numberOfGrids - * option when instantiating hashgrid. - * e.g. - * - * var hg = new Hashgrid({ - * numberOfGrids: 2 - * }); - */ -#hashgrid.hashgrid2, -#hashgrid.hashgrid2 .hashgrid-column-container{ - /* Container width adjustments */ - padding: 0 160px; - width: 660px; -} - -#hashgrid.hashgrid2 .hashgrid__column{ - /* Vertical grid line colour for grid 2 */ - border-color: crimson; -} -</textarea></li> -<li><h3>Modify #grid to suit your needs</h3> -<p>The CSS and JavaScript is annotated to help you.</p></li> -</ol> - -<h2 id="usage">Usage</h2> -<p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p> -<dl> -<dt><span class="key">g</span></dt> -<dd>Show the grid until you release.</dd> -<dt><span class="key">g</span> + <span class="key">h</span></dt> -<dd>Show and hold the grid (<span class="key">g</span> will remove it again).</dd> -<dt><span class="key">g</span> + <span class="key">f</span></dt> -<dd>Toggle the grid to the foreground and back. Pressing <span class="key">f</span> while the grid is held also works.</dd> -<dt><span class="key">g</span> + <span class="key">j</span></dt> -<dd>Jump to the next grid. Pressing <span class="key">j</span> while the grid is held also works.</dd> -</dl> -<p><em>N.B. Hashgrid remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page except in Chrome v4, Safari v4, Firefox v3.6, or more recent versions.</em></p> - -<h2 id="release-notes">Release Notes</h2> -<dl> -<dt>v10&#8201;&#8212;&#8201;30 Nov 2015</dt> -<dd>jQuery is no longer required.</dd> -<dt>v9&#8201;&#8212;&#8201;30 May 2013</dt> -<dd>Minor release: Improved example usage to avoid conflicts.</dd> -<dt>v8&#8201;&#8212;&#8201;6 Oct 2012</dt> -<dd> -<ul> -<li>Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="http://www.tomarnold.de/">Tom Arnold</a>.</li> -<li>Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="http://lynx.io/">Callum Macrae</a>.</li> -<li>Fixes to cookie handling. Thanks to <a href="http://loonypandora.co.uk/">James Aitken</a>.</li> -<li>Optimisations.</li> -</ul> -</dd> -<dt>v7&#8201;&#8212;&#8201;11 Jun 2011</dt> -<dd>Minor release: Updated license references.</dd> -<dt>v6&#8201;&#8212;&#8201;10 Jun 2011</dt> -<dd>Minor release: Optimisations (thanks to <a href="http://andrewjaswa.com/">Andrew Jaswa</a> for contributions), and now released under an Apache License.</dd> -<dt>v5&#8201;&#8212;&#8201;3 Nov 2010</dt> -<dd> -<ul> -<li>Vertical grid lines can now be set using CSS&#8230; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution.</li> -<li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li> -<li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback.</li> -</ul> -</dd> -<dt>v4&#8201;&#8212;&#8201;29 Mar 2010</dt> -<dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd> -<dt>v3&#8201;&#8212;&#8201;22 Feb 2010</dt> -<dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd> -<dt>v2&#8201;&#8212;&#8201;2 Feb 2010</dt> -<dd> -<ul> -<li>Keys are now more easily configured (see top of hashgrid.js).</li> -<li>Fixed crash when using with disabled CSS.</li> -<li>Renamed the GridOverlay object to hashgrid.</li> -</ul> -</dd> -<dt>v1&#8201;&#8212;&#8201;21 Dec 2009</dt> -<dd>First release.</dd> -</dl> - -<h2 id="known-issues">Known Issues</h2> -<ul> -<li><del>IE 8: Fully functional, but the default <span class="key">ALT</span> + <span class="key">G</span> + <span class="key">ENTER</span> shortcut puts IE into full screen mode. Hit <span class="key">ALT</span> + <span class="key">ENTER</span> to toggle full screen mode off again.</del><ins datetime="2010-02-22"> The default keyboard shortcuts have been changed.</ins></li> -<li>IE 6: The grid is always in the foreground.</li> -<li>Opera 9/10: Using <span class="key">CTRL</span> or <span class="key">ALT</span> as a modifier key will not work due to different key handling by the browser.</li> -</ul> - -<h2 id="license">License</h2> - -<p>Copyright 2013 Analog Coop Limited</p> - -<p>Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at<br /><br /> - -<a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a></p> - -<p>Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License.</p> - -<p>This essentially means that you&#8217;re free to copy, modify and distribute it for any project so long as you provide clear attribution to Analog Coop Limited. <a href="http://analog.coop/#talk-to-us">Contact us</a> if you need a different license.</p> - -<div id="footer" role="contentinfo"> -<p>#grid is an <a href="http://analog.coop/">Analog</a> gig. It was conceived by <a href="http://jontangerine.com/">Jon Tan</a>, and built by <a href="http://accessibility.co.uk/">Jon Gibbins</a>, in cahoots with our <a href="http://analog.coop#is">fine friends</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p> -</div> - -</div> - -<!-- Include the hashgrid script --> -<script type="text/javascript" src="dist/javascripts/hashgrid.js"></script> - -<!-- Kick hashgrid into action --> -<script> -var hg = new Hashgrid({ - numberOfGrids: 2 -}); -</script> - -</body> - -</html> diff --git a/index.html b/index.html new file mode 100644 index 0000000..7d470f1 --- /dev/null +++ b/index.html @@ -0,0 +1,307 @@ +<!DOCTYPE html><html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>#grid</title><!-- Demo styles--><style type="text/css">/* Putting inline rules here so the document can be downloaded with style */ + +body{ +font-size: 1em; +line-height: 1.25; +font-family: Arial, sans-serif; +background: White; +color: DimGray; +margin: 0; +} +#content{ +font-size: 16px; +line-height: 20px; +position: relative; +} +#content{ +width: 620px; +margin: 0 auto; +} +#footer{ +border-top: 1px dotted DarkGray; +padding-top: 19px; +} +h1, h2{ +color: Black; +font-weight: normal; +} +h1{ +font-size: 36px; +line-height: 40px; +margin: 40px 0 20px; +padding-bottom: 19px; +border-bottom: 1px dotted DarkGray; +} +h1 em{ +font-style: normal; +color: DarkGray; +font-size: 16px; +line-height: 20px; +margin: 0 0 20px; +} +h2, h3{ +font-size: 16px; +font-weight: 700; +line-height: 20px; +margin: 0 0 20px; +} +h3{ +font-weight: 300; +} +a:link, +a:visited{ +color: Black; +text-decoration: none; +padding: 0 2px; +background-color: WhiteSmoke; +border-bottom: 1px solid Gold; +} +a:focus{ +outline: none; +} +a:focus, +a:hover, +a:active{ +background-color: Khaki; +border-bottom: 1px solid GoldenRod; +} +p, ul{ +padding: 0; +margin: 0 0 20px; +} +dl, ol{ +padding: 0; +margin: 0; +} +ul{ +list-style: circle; +} +ol li{ +margin-bottom: 20px; +} +dd{ +margin: 0 0 20px 0; +} +del{ +text-decoration: line-through; +opacity: 0.75; +} +ins{ +text-decoration: none; +} +code{ +font-size: 14px; +line-height: 1; +} +textarea{ +font-family: 'Courier New', monospace; +font-size: 14px; +line-height: 20px; +display: block; +width: 600px; +margin: 0 0 20px; +padding: 0 0 0 15px; +border: 0; +color: Black; +background: Gainsboro; +border-left: 5px solid DarkGray; +} +#javascript-code{ +height: 320px; +} +#css-code{ +height: 1580px; +} +.summary em{ +font-style: normal; +position: absolute; +color: DarkGray; +right: 0; +top: 18px; +width: 140px; +} +.summary em span{ +position: absolute; +left: -9999px; +} +#download{ +line-height: 60px; +padding: 0 40px 0 15px; +border-left: 5px solid DarkGray; +background: Gainsboro; +color: DimGray; +} +span.key{ +color: Black; +text-transform: uppercase; +} +</style><!-- Hashgrid styles--><style type="text/css">/** + * Grid + */ +#hashgrid{ + /* + * Spreads the whole page by default + * Adjust to match your container + */ + /*width: 100%;*/ + width: 980px; + position: absolute; + height: 100%; + top: 0; + left: 50%; + margin-left: -490px; + overflow: hidden; +} + +.hashgrid-column-container { + position: absolute; + height: 100%; + width: 100%; + top: 0; + left: 0; +} + +/** + * Vertical grid lines + * + * Set the column width taking the borders into consideration, + * and use margins to set column gutters. + */ +.hashgrid__column{ + width: 139px; + border: solid darkturquoise; + border-width: 0 1px; + margin-left: 19px; + height: 100%; + float: left; +} + +/** + * Horizontal grid lines, defined by your base line height + * + * Remember, the CSS properties that define the box model: + * visible height = height + borders + margins + padding + */ +.hashgrid__row{ + /* 20px line height */ + height: 19px; + border-bottom: 1px dotted darkgray; + margin: 0; + padding: 0; +} + +/** + * Classes for multiple grids + * + * When using more than one grid, remember to set the numberOfGrids + * option when instantiating hashgrid. + * e.g. + * + * var hg = new Hashgrid({ + * numberOfGrids: 2 + * }); + */ +#hashgrid.hashgrid2, +#hashgrid.hashgrid2 .hashgrid-column-container{ + /* Container width adjustments */ + padding: 0 160px; + width: 660px; +} + +#hashgrid.hashgrid2 .hashgrid__column{ + /* Vertical grid line colour for grid 2 */ + border-color: crimson; +} +</style></head><body><div id="content" role="main"><h1>#grid&nbsp;<em>v10</em></h1><p class="summary"><em>Mon, 30 Nov 2015<span>:</span></em>This is a little tool we created for our&nbsp;<a href="http://analog.coop/">Analog&#160;holding&#160;page</a>. It inserts a&nbsp;<a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a>&nbsp;in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit&nbsp;<span class="key">g</span> on your keyboard.</p><h2>Download</h2><p id="download"><a href="https://github.com/dotjay/hashgrid/downloads">Download #grid</a>&nbsp;from&nbsp;<a href="https://github.com/dotjay/hashgrid">GitHub</a></p><h2 id="features">Features</h2><ul><li>Adaptable for all layout widths and alignments</li><li>Adaptable for any vertical rhythm value</li><li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li><li>Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters</li></ul><p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p><h2 id="installation">Installation</h2><ol><li><h3>Copy the&nbsp;<a href="https://github.com/dotjay/hashgrid/blob/v9/hashgrid.js">hashgrid.js</a>&nbsp;script to your project</h3></li><li><h3>Add this script to your page(s) just before the closing <code>&#60;/body&#62;</code> tag</h3><textarea id="javascript-code" cols="68" rows="15" readonly="readonly">&#60;!-- Include the hashgrid script --&#62; +&#60;script type="text/javascript" src="hashgrid.js"&#62;&#60;/script&#62; + +&#60;!-- Kick hashgrid into action --&#62; +&#60;script type="text/javascript"&#62; +var grid = new Hashgrid({ numberOfGrids: 2 }); +&#60;/script&#62; + +&#60;!-- Note: Use window onload if your css is not inlined --&#62; +&#60;script type="text/javascript"&#62; +window.addEventListener("load", function(event) { + var grid = new Hashgrid({ numberOfGrids: 2 }); +}); +&#60;/script&#62;</textarea></li><li><h3>Add the CSS to your page(s)</h3><textarea id="css-code" cols="68" rows="64" readonly="readonly">/** + * Grid + */ +#hashgrid{ + /* + * Spreads the whole page by default + * Adjust to match your container + */ + /*width: 100%;*/ + width: 980px; + position: absolute; + height: 100%; + top: 0; + left: 50%; + margin-left: -490px; + overflow: hidden; +} + +.hashgrid-column-container { + position: absolute; + height: 100%; + width: 100%; + top: 0; + left: 0; +} + +/** + * Vertical grid lines + * + * Set the column width taking the borders into consideration, + * and use margins to set column gutters. + */ +.hashgrid__column{ + width: 139px; + border: solid darkturquoise; + border-width: 0 1px; + margin-left: 19px; + height: 100%; + float: left; +} + +/** + * Horizontal grid lines, defined by your base line height + * + * Remember, the CSS properties that define the box model: + * visible height = height + borders + margins + padding + */ +.hashgrid__row{ + /* 20px line height */ + height: 19px; + border-bottom: 1px dotted darkgray; + margin: 0; + padding: 0; +} + +/** + * Classes for multiple grids + * + * When using more than one grid, remember to set the numberOfGrids + * option when instantiating hashgrid. + * e.g. + * + * var hg = new Hashgrid({ + * numberOfGrids: 2 + * }); + */ +#hashgrid.hashgrid2, +#hashgrid.hashgrid2 .hashgrid-column-container{ + /* Container width adjustments */ + padding: 0 160px; + width: 660px; +} + +#hashgrid.hashgrid2 .hashgrid__column{ + /* Vertical grid line colour for grid 2 */ + border-color: crimson; +} +</textarea></li><li><h3>Modify #grid to suit your needs</h3><p>The CSS and JavaScript is annotated to help you.</p></li></ol><h2 id="usage">Usage</h2><p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p><dl><dt><span class="key">g</span></dt><dd>Show the grid until you release.</dd><dt><span class="key">g</span> + <span class="key">h</span></dt><dd>Show and hold the grid (<span class="key">g</span> will remove it again).</dd><dt><span class="key">g</span> + <span class="key">f</span></dt><dd>Toggle the grid to the foreground and back. Pressing <span class="key">f</span> while the grid is held also works.</dd><dt><span class="key">g</span> + <span class="key">j</span></dt><dd>Jump to the next grid. Pressing <span class="key">j</span> while the grid is held also works.</dd></dl><p><em>N.B. Hashgrid remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page except in Chrome v4, Safari v4, Firefox v3.6, or more recent versions.</em></p><h2 id="release-notes">Release Notes</h2><dl><dt>v10&#8201;&#8212;&#8201;30 Nov 2015</dt><dd>jQuery is no longer required.</dd><dt>v9&#8201;&#8212;&#8201;30 May 2013</dt><dd>Minor release: Improved example usage to avoid conflicts.</dd><dt>v8&#8201;&#8212;&#8201;6 Oct 2012</dt><dd><ul><li>Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="http://www.tomarnold.de/">Tom Arnold</a>.</li><li>Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="http://lynx.io/">Callum Macrae</a>.</li><li>Fixes to cookie handling. Thanks to <a href="http://loonypandora.co.uk/">James Aitken</a>.</li><li>Optimisations.</li></ul></dd><dt>v7&#8201;&#8212;&#8201;11 Jun 2011</dt><dd>Minor release: Updated license references.</dd><dt>v6&#8201;&#8212;&#8201;10 Jun 2011</dt><dd>Minor release: Optimisations (thanks to <a href="http://andrewjaswa.com/">Andrew Jaswa</a> for contributions), and now released under an Apache License.</dd><dt>v5&#8201;&#8212;&#8201;3 Nov 2010</dt><dd><ul><li>Vertical grid lines can now be set using CSS&#8230; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution.</li><li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li><li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback.</li></ul></dd><dt>v4&#8201;&#8212;&#8201;29 Mar 2010</dt><dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd><dt>v3&#8201;&#8212;&#8201;22 Feb 2010</dt><dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd><dt>v2&#8201;&#8212;&#8201;2 Feb 2010</dt><dd><ul><li>Keys are now more easily configured (see top of hashgrid.js).</li><li>Fixed crash when using with disabled CSS.</li><li>Renamed the GridOverlay object to hashgrid.</li></ul></dd><dt>v1&#8201;&#8212;&#8201;21 Dec 2009</dt><dd>First release.</dd></dl><h2 id="known-issues">Known Issues</h2><ul><li><del>IE 8: Fully functional, but the default <span class="key">ALT</span> + <span class="key">G</span> + <span class="key">ENTER</span> shortcut puts IE into full screen mode. Hit <span class="key">ALT</span> + <span class="key">ENTER</span> to toggle full screen mode off again.</del><ins datetime="2010-02-22"> The default keyboard shortcuts have been changed.</ins></li><li>IE 6: The grid is always in the foreground.</li><li>Opera 9/10: Using <span class="key">CTRL</span> or <span class="key">ALT</span> as a modifier key will not work due to different key handling by the browser.</li></ul><h2 id="license">License</h2><p>Copyright 2013 Analog Coop Limited</p><p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br/></p><a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a><p><br/>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.</p><p>This essentially means that you&#8217;re free to copy, modify and distribute it for any project so long as you provide clear attribution to Analog Coop Limited. <a href="http://analog.coop/#talk-to-us">Contact us</a> if you need a different license.</p><div id="footer" role="contentinfo"><p>#grid is an <a href="http://analog.coop/">Analog</a> gig. It was conceived by <a href="http://jontangerine.com/">Jon Tan</a>, and built by <a href="http://accessibility.co.uk/">Jon Gibbins</a>, in cahoots with our <a href="http://analog.coop#is">fine friends</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p></div></div><!-- Include the hashgrid script--><script type="text/javascript" src="dist/javascripts/hashgrid.js"></script><!-- Kick hashgrid into action--><script>var hg = new Hashgrid({ + numberOfGrids: 2 +});</script></body></html> \ No newline at end of file diff --git a/package.json b/package.json index 4a70fd8..9787e5b 100644 --- a/package.json +++ b/package.json @@ -1,30 +1,32 @@ { "name": "hashgrid", "version": "9.0.0", "description": "A little tool that inserts a layout grid in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background.", "main": "hashgrid.js", "scripts": { "test": "./node_modules/.bin/hihat tests/*.js -p tap-dev-tool" }, "repository": { "type": "git", "url": "git+https://github.com/widatama/hashgrid.git" }, "author": "", "license": "Apache-2.0", "bugs": { "url": "https://github.com/widatama/hashgrid/issues" }, "homepage": "https://github.com/widatama/hashgrid#readme", "devDependencies": { "grunt": "^0.4.5", "grunt-contrib-clean": "^0.7.0", "grunt-contrib-concat": "^0.5.1", + "grunt-contrib-jade": "^0.15.0", + "grunt-contrib-less": "^1.1.0", "grunt-contrib-uglify": "^0.11.0", "grunt-contrib-watch": "^0.6.1", "hihat": "^2.5.0", "load-grunt-config": "^0.19.0", "tap-dev-tool": "^1.3.0", "tape": "^4.2.2" } } diff --git a/src/index.jade b/src/index.jade new file mode 100644 index 0000000..34ec6cf --- /dev/null +++ b/src/index.jade @@ -0,0 +1,160 @@ +doctype html + +html(lang="en") + + head + meta(http-equiv="Content-Type", content="text/html; charset=utf-8") + title #grid + + // Demo styles + style(type="text/css") + + include ./partial/demo.css + + // Hashgrid styles + style(type="text/css") + + include ./partial/hashgrid.css + + body + #content(role="main") + + h1 + | #grid&nbsp; + em v10 + + p.summary + em Mon, 30 Nov 2015 + span : + | This is a little tool we created for our&nbsp; + a(href="http://analog.coop/") Analog&#160;holding&#160;page + | . It inserts a&nbsp; + a(href="http://en.wikipedia.org/wiki/Grid_(page_layout)") layout grid + | &nbsp;in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit&nbsp; + span(class="key") g + | on your keyboard. + + h2 Download + + p#download + a(href="https://github.com/dotjay/hashgrid/downloads") Download #grid + | &nbsp;from&nbsp; + a(href="https://github.com/dotjay/hashgrid") GitHub + + h2#features Features + + ul + li Adaptable for all layout widths and alignments + li Adaptable for any vertical rhythm value + li Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids + li Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters + + p #grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids. + + h2#installation Installation + + ol + li + h3 Copy the&nbsp; + a(href="https://github.com/dotjay/hashgrid/blob/v9/hashgrid.js") hashgrid.js + | &nbsp;script to your project + + li + h3 Add this script to your page(s) just before the closing <code>&#60;/body&#62;</code> tag + + include ./partial/js_code.jade + + li + h3 Add the CSS to your page(s) + + include ./partial/css_code.jade + + li + h3 Modify #grid to suit your needs + p The CSS and JavaScript is annotated to help you. + + h2#usage Usage + + p The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first. + + dl + dt <span class="key">g</span> + dd Show the grid until you release. + dt <span class="key">g</span> + <span class="key">h</span> + dd Show and hold the grid (<span class="key">g</span> will remove it again). + dt <span class="key">g</span> + <span class="key">f</span> + dd Toggle the grid to the foreground and back. Pressing <span class="key">f</span> while the grid is held also works. + dt <span class="key">g</span> + <span class="key">j</span> + dd Jump to the next grid. Pressing <span class="key">j</span> while the grid is held also works. + + p <em>N.B. Hashgrid remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page except in Chrome v4, Safari v4, Firefox v3.6, or more recent versions.</em> + + h2#release-notes Release Notes + + dl + dt v10&#8201;&#8212;&#8201;30 Nov 2015 + dd jQuery is no longer required. + dt v9&#8201;&#8212;&#8201;30 May 2013 + dd Minor release: Improved example usage to avoid conflicts. + dt v8&#8201;&#8212;&#8201;6 Oct 2012 + dd + ul + li Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="http://www.tomarnold.de/">Tom Arnold</a>. + li Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="http://lynx.io/">Callum Macrae</a>. + li Fixes to cookie handling. Thanks to <a href="http://loonypandora.co.uk/">James Aitken</a>. + li Optimisations. + dt v7&#8201;&#8212;&#8201;11 Jun 2011 + dd Minor release: Updated license references. + dt v6&#8201;&#8212;&#8201;10 Jun 2011 + dd Minor release: Optimisations (thanks to <a href="http://andrewjaswa.com/">Andrew Jaswa</a> for contributions), and now released under an Apache License. + dt v5&#8201;&#8212;&#8201;3 Nov 2010 + dd + ul + li Vertical grid lines can now be set using CSS&#8230; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution. + li Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property. + li Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback. + dt v4&#8201;&#8212;&#8201;29 Mar 2010 + dd Fixes for multiple grid support under WebKit (Safari and Chrome). + dt v3&#8201;&#8212;&#8201;22 Feb 2010 + dd Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms. + dt v2&#8201;&#8212;&#8201;2 Feb 2010 + dd + ul + li Keys are now more easily configured (see top of hashgrid.js). + li Fixed crash when using with disabled CSS. + li Renamed the GridOverlay object to hashgrid. + dt v1&#8201;&#8212;&#8201;21 Dec 2009 + dd First release. + + h2#known-issues Known Issues + + ul + li <del>IE 8: Fully functional, but the default <span class="key">ALT</span> + <span class="key">G</span> + <span class="key">ENTER</span> shortcut puts IE into full screen mode. Hit <span class="key">ALT</span> + <span class="key">ENTER</span> to toggle full screen mode off again.</del><ins datetime="2010-02-22"> The default keyboard shortcuts have been changed.</ins> + li IE 6: The grid is always in the foreground. + li Opera 9/10: Using <span class="key">CTRL</span> or <span class="key">ALT</span> as a modifier key will not work due to different key handling by the browser. + + h2#license License + + p Copyright 2013 Analog Coop Limited + + p Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br/> + + a(href="http://www.apache.org/licenses/LICENSE-2.0") http://www.apache.org/licenses/LICENSE-2.0 + + p <br/>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + + p This essentially means that you&#8217;re free to copy, modify and distribute it for any project so long as you provide clear attribution to Analog Coop Limited. <a href="http://analog.coop/#talk-to-us">Contact us</a> if you need a different license. + + + div#footer(role="contentinfo") + p #grid is an <a href="http://analog.coop/">Analog</a> gig. It was conceived by <a href="http://jontangerine.com/">Jon Tan</a>, and built by <a href="http://accessibility.co.uk/">Jon Gibbins</a>, in cahoots with our <a href="http://analog.coop#is">fine friends</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only. + + + // Include the hashgrid script + script(type="text/javascript" src="dist/javascripts/hashgrid.js") + + // Kick hashgrid into action + script. + var hg = new Hashgrid({ + numberOfGrids: 2 + }); diff --git a/src/cookieStorage.js b/src/javascripts/cookieStorage.js similarity index 100% rename from src/cookieStorage.js rename to src/javascripts/cookieStorage.js diff --git a/src/hashgrid.js b/src/javascripts/hashgrid.js similarity index 100% rename from src/hashgrid.js rename to src/javascripts/hashgrid.js diff --git a/src/helper.js b/src/javascripts/helper.js similarity index 100% rename from src/helper.js rename to src/javascripts/helper.js diff --git a/src/sessionStorage.js b/src/javascripts/sessionStorage.js similarity index 100% rename from src/sessionStorage.js rename to src/javascripts/sessionStorage.js diff --git a/src/storage.js b/src/javascripts/storage.js similarity index 100% rename from src/storage.js rename to src/javascripts/storage.js diff --git a/src/partial/css_code.jade b/src/partial/css_code.jade new file mode 100644 index 0000000..c129b70 --- /dev/null +++ b/src/partial/css_code.jade @@ -0,0 +1,3 @@ +textarea#css-code(cols="68" rows="64" readonly="readonly") + + include ./hashgrid.css diff --git a/src/partial/demo.css b/src/partial/demo.css new file mode 100644 index 0000000..d8674e6 --- /dev/null +++ b/src/partial/demo.css @@ -0,0 +1,137 @@ +/* Putting inline rules here so the document can be downloaded with style */ + +body{ +font-size: 1em; +line-height: 1.25; +font-family: Arial, sans-serif; +background: White; +color: DimGray; +margin: 0; +} +#content{ +font-size: 16px; +line-height: 20px; +position: relative; +} +#content{ +width: 620px; +margin: 0 auto; +} +#footer{ +border-top: 1px dotted DarkGray; +padding-top: 19px; +} +h1, h2{ +color: Black; +font-weight: normal; +} +h1{ +font-size: 36px; +line-height: 40px; +margin: 40px 0 20px; +padding-bottom: 19px; +border-bottom: 1px dotted DarkGray; +} +h1 em{ +font-style: normal; +color: DarkGray; +font-size: 16px; +line-height: 20px; +margin: 0 0 20px; +} +h2, h3{ +font-size: 16px; +font-weight: 700; +line-height: 20px; +margin: 0 0 20px; +} +h3{ +font-weight: 300; +} +a:link, +a:visited{ +color: Black; +text-decoration: none; +padding: 0 2px; +background-color: WhiteSmoke; +border-bottom: 1px solid Gold; +} +a:focus{ +outline: none; +} +a:focus, +a:hover, +a:active{ +background-color: Khaki; +border-bottom: 1px solid GoldenRod; +} +p, ul{ +padding: 0; +margin: 0 0 20px; +} +dl, ol{ +padding: 0; +margin: 0; +} +ul{ +list-style: circle; +} +ol li{ +margin-bottom: 20px; +} +dd{ +margin: 0 0 20px 0; +} +del{ +text-decoration: line-through; +opacity: 0.75; +} +ins{ +text-decoration: none; +} +code{ +font-size: 14px; +line-height: 1; +} +textarea{ +font-family: 'Courier New', monospace; +font-size: 14px; +line-height: 20px; +display: block; +width: 600px; +margin: 0 0 20px; +padding: 0 0 0 15px; +border: 0; +color: Black; +background: Gainsboro; +border-left: 5px solid DarkGray; +} +#javascript-code{ +height: 320px; +} +#css-code{ +height: 1580px; +} +.summary em{ +font-style: normal; +position: absolute; +color: DarkGray; +right: 0; +top: 18px; +width: 140px; +} +.summary em span{ +position: absolute; +left: -9999px; +} +#download{ +line-height: 60px; +padding: 0 40px 0 15px; +border-left: 5px solid DarkGray; +background: Gainsboro; +color: DimGray; +} +span.key{ +color: Black; +text-transform: uppercase; +} diff --git a/src/partial/hashgrid.css b/src/partial/hashgrid.css new file mode 100644 index 0000000..2fd2a7d --- /dev/null +++ b/src/partial/hashgrid.css @@ -0,0 +1,77 @@ +/** + * Grid + */ +#hashgrid{ + /* + * Spreads the whole page by default + * Adjust to match your container + */ + /*width: 100%;*/ + width: 980px; + position: absolute; + height: 100%; + top: 0; + left: 50%; + margin-left: -490px; + overflow: hidden; +} + +.hashgrid-column-container { + position: absolute; + height: 100%; + width: 100%; + top: 0; + left: 0; +} + +/** + * Vertical grid lines + * + * Set the column width taking the borders into consideration, + * and use margins to set column gutters. + */ +.hashgrid__column{ + width: 139px; + border: solid darkturquoise; + border-width: 0 1px; + margin-left: 19px; + height: 100%; + float: left; +} + +/** + * Horizontal grid lines, defined by your base line height + * + * Remember, the CSS properties that define the box model: + * visible height = height + borders + margins + padding + */ +.hashgrid__row{ + /* 20px line height */ + height: 19px; + border-bottom: 1px dotted darkgray; + margin: 0; + padding: 0; +} + +/** + * Classes for multiple grids + * + * When using more than one grid, remember to set the numberOfGrids + * option when instantiating hashgrid. + * e.g. + * + * var hg = new Hashgrid({ + * numberOfGrids: 2 + * }); + */ +#hashgrid.hashgrid2, +#hashgrid.hashgrid2 .hashgrid-column-container{ + /* Container width adjustments */ + padding: 0 160px; + width: 660px; +} + +#hashgrid.hashgrid2 .hashgrid__column{ + /* Vertical grid line colour for grid 2 */ + border-color: crimson; +} diff --git a/src/partial/js_code.jade b/src/partial/js_code.jade new file mode 100644 index 0000000..1738fcc --- /dev/null +++ b/src/partial/js_code.jade @@ -0,0 +1,16 @@ +textarea#javascript-code(cols="68" rows="15" readonly="readonly"). + + &#60;!-- Include the hashgrid script --&#62; + &#60;script type="text/javascript" src="hashgrid.js"&#62;&#60;/script&#62; + + &#60;!-- Kick hashgrid into action --&#62; + &#60;script type="text/javascript"&#62; + var grid = new Hashgrid({ numberOfGrids: 2 }); + &#60;/script&#62; + + &#60;!-- Note: Use window onload if your css is not inlined --&#62; + &#60;script type="text/javascript"&#62; + window.addEventListener("load", function(event) { + var grid = new Hashgrid({ numberOfGrids: 2 }); + }); + &#60;/script&#62; diff --git a/tests/cookieStorage.js b/tests/cookieStorage.js index 0765591..f758079 100644 --- a/tests/cookieStorage.js +++ b/tests/cookieStorage.js @@ -1,20 +1,20 @@ var tape = require("tape"); -var CookieStorage = require("../src/cookieStorage"); +var CookieStorage = require("../src/javascripts/cookieStorage"); tape("Cookie Storage module", function(assert) { var storage = new CookieStorage(); var cookieLabel = "label"; var cookieValue = "value"; assert.equal(storage.read(cookieLabel), null, "Cookie reading returns null if cookie value is not set"); assert.ok(storage.write(cookieLabel, cookieValue), "Cookie writing returns written value"); assert.equal(storage.read(cookieLabel), cookieValue, "Cookie writing sets valid cookie value"); assert.equal(storage.remove(cookieLabel), cookieValue, "Cookie removal returns removed value"); assert.equal(storage.read(cookieLabel), null, "Cookie reading returns null after cookie value is removed"); assert.end(); }); diff --git a/tests/hashgrid.js b/tests/hashgrid.js index efbc082..a695e8a 100644 --- a/tests/hashgrid.js +++ b/tests/hashgrid.js @@ -1,35 +1,35 @@ var tape = require("tape"); -var Hashgrid = require("../src/hashgrid"); +var Hashgrid = require("../src/javascripts/hashgrid"); function setupDOM() { document.body.style.height = "100px"; } tape("Hashgrid module", function(assert) { var hashgrid; var hashgridOptions = { id: "hashgrid" }; var hashgridEl; setupDOM(); hashgrid = new Hashgrid(hashgridOptions); hashgridEl = document.querySelector("#" + hashgridOptions.id); assert.ok(hashgridEl, "Hashgrid created"); hashgrid.showOverlay(); assert.equal(hashgridEl.style.display, "block", "Hashgrid shown"); hashgrid.hideOverlay(); assert.equal(hashgridEl.style.display, "none", "Hashgrid hidden"); hashgrid.destroy(); hashgridEl = document.querySelector("#" + hashgridOptions.id); assert.notOk(hashgridEl, "Hashgrid destroyed"); assert.end(); }); diff --git a/tests/helper.js b/tests/helper.js index 51873cd..dc0d4d5 100644 --- a/tests/helper.js +++ b/tests/helper.js @@ -1,97 +1,97 @@ var tape = require("tape"); -var Helper = require("../src/helper"); +var Helper = require("../src/javascripts/helper"); function setupKeyboardEvent(keyCode, keyModifier) { // So much for dispatching event, sigh var kbdEvent = new KeyboardEvent("keydown"); var initMethod = kbdEvent.initKeyboardEvent ? "initKeyboardEvent" : "initKeyEvent"; Object.defineProperty(kbdEvent, "keyCode", { get: function() { return this.keyCodeVal; } }); Object.defineProperty(kbdEvent, "which", { get: function() { return this.keyCodeVal; } }); if(keyModifier) { Object.defineProperty(kbdEvent, keyModifier + "Key", { get: function() { return this.keyModifierVal; } }); } kbdEvent[initMethod]( "keydown", true, true, window, keyModifier === "ctrl" ? true : false, keyModifier === "alt" ? true : false, keyModifier === "shift" ? true : false, keyModifier === "metaKey" ? true : false, keyCode, 0 ); kbdEvent.keyCodeVal = keyCode; kbdEvent.keyModifierVal = true; return kbdEvent; } tape("Helper module", function(assert) { var obj1 = { a: 1, b: 2 }; var obj2 = { a: 2, c: 3 }; var obj3 = { a: 2, b: 2, c: 3 }; var keyCode = "a"; var keyModifier = "alt"; var kbdEvent = setupKeyboardEvent(keyCode.charCodeAt(0), keyModifier); assert.plan(2); assert.test("Object merge", function(assert) { assert.plan(5); assert.deepEqual(Helper.mergeObjects(), {}, "Returns an empty object when called without any arguments"); assert.deepEqual(Helper.mergeObjects("string"), {}, "Returns an empty object when one of the arguments is not an object"); assert.deepEqual(Helper.mergeObjects(obj1), obj1, "Returns the only available object for merge"); assert.deepEqual(Helper.mergeObjects(obj1, obj2), obj3, "Two objects merged properly"); assert.deepEqual(Helper.mergeObjects({}, obj1, obj2), obj3, "Three objects merged properly"); }); assert.test("Keyboard event helper", function(assert) { assert.plan(2); var keydownHandler = function(event) { assert.equal(Helper.getKey(event), keyCode, "Event keyCode obtained"); assert.ok(Helper.getKeyModifier(event, keyModifier), "Event keyModifier obtained"); }; document.addEventListener("keydown", keydownHandler); document.documentElement.dispatchEvent(kbdEvent); document.removeEventListener("keydown", keydownHandler); }); }); diff --git a/tests/sessionStorage.js b/tests/sessionStorage.js index 59780cc..26382a9 100644 --- a/tests/sessionStorage.js +++ b/tests/sessionStorage.js @@ -1,22 +1,22 @@ var tape = require("tape"); -var SessionStorage = require("../src/sessionStorage"); +var SessionStorage = require("../src/javascripts/sessionStorage"); tape("Session Storage module", function(assert) { var storage = new SessionStorage(); var dataLabel = "label"; var dataValue = "value"; window.sessionStorage.clear(); assert.equal(storage.read(dataLabel), null, "Data reading returns null if data value is not set"); assert.ok(storage.write(dataLabel, dataValue), "Data writing returns written value"); assert.equal(storage.read(dataLabel), dataValue, "Data writing sets valid data value"); assert.equal(storage.remove(dataLabel), dataValue, "Data removal returns removed value"); assert.equal(storage.read(dataLabel), null, "Data reading returns null after data value is removed"); assert.end(); });
dotjay/hashgrid
d0f0a11d1bc743260cc823c26c3dff03708b2472
Tidy up with eslint
diff --git a/src/hashgrid.js b/src/hashgrid.js index 06cdbff..8e2e87b 100644 --- a/src/hashgrid.js +++ b/src/hashgrid.js @@ -1,404 +1,404 @@ /** * hashgrid (vanilla version) * http://github.com/dotjay/hashgrid * Version 10, 25 Nov 2015 * Written by Jon Gibbins at Analog, http://analog.coop/ * * Contibutors: * Sean Coates, http://seancoates.com/ * Phil Dokas, http://jetless.org/ * Andrew Jaswa, http://andrewjaswa.com/ * * License: * http://www.apache.org/licenses/LICENSE-2.0.html * * // Using a basic #grid setup * var grid = new Hashgrid(); * * // Using #grid with a custom id (e.g. #mygrid) * var grid = new Hashgrid("mygrid"); * * // Using #grid with additional options * var grid = new hashgrid({ * id: "mygrid", // id for the grid container * modifierKey: "alt", // optional "ctrl", "alt" or "shift" * showGridKey: "s", // key to show the grid * holdGridKey: "enter", // key to hold the grid shown * foregroundKey: "f", // key to toggle foreground/background * jumpGridsKey: "d", // key to cycle through the grids * numberOfGrids: 2, // number of grids * classPrefix: "mygrid", // prefix for rows and columns * storagePrefix: "mygrid" // prefix for storage label * }); */ // REMOVE START // -if (typeof module!="undefined" && module.exports) { - var Storage = require("./storage"); +if (typeof module != "undefined" && module.exports) { + var SimpleStorage = require("./storage"); var Helper = require("./helper"); } // REMOVE END // var Hashgrid = (function() { "use strict"; var - storage = new Storage(), + storage = new SimpleStorage(), fillGrid, boundKeydownHandler, keydownHandler, boundKeyupHandler, keyupHandler, createStorageData; // Constructor function Hashgrid(customOptions) { var defaultOptions = { id: "hashgrid", // id for the grid container modifierKey: null, // optional "ctrl", "alt" or "shift" showGridKey: "g", // key to show the grid holdGridKey: "h", // key to hold the grid shown foregroundKey: "f", // key to toggle foreground/background jumpGridsKey: "j", // key to cycle through the grids numberOfGrids: 1, // number of grids classPrefix: "hashgrid", // prefix for rows and columns storagePrefix: "hashgrid" // prefix for storage label }, privateOptions = { overlayZBG: "-1", overlayZFG: "9999" }; // Apply options this.options = Helper.mergeObjects(defaultOptions, customOptions, privateOptions); this.state = { overlayHold: false, overlayOn: false, overlayZIndex: "B", isKeyDown: {}, gridNumber: 1 }; this.init(); } // Instance methods Hashgrid.prototype.init = function() { var storageData; // Create overlay, hidden before adding to DOM this.overlay = document.createElement("div"); this.overlay.id = this.options.id; this.overlay.classList.add(this.options.classPrefix + this.state.gridNumber); this.overlay.style.display = "none"; this.overlay.style.pointerEvents = "none"; this.overlay.style.height = document.body.scrollHeight + "px"; // Unless a custom z-index is set, ensure the overlay will be behind everything if(this.overlay.style.zIndex === "auto") { this.overlay.style.zIndex = this.overlayZBackground; } // Prepend overlay to body document.body.insertBefore(this.overlay, document.body.firstChild); // Add keyboard events listener boundKeydownHandler = keydownHandler.bind(this); boundKeyupHandler = keyupHandler.bind(this); if(document.addEventListener) { document.addEventListener("keydown", boundKeydownHandler, false); document.addEventListener("keyup", boundKeyupHandler, false); } else if(document.attachEvent){ document.attachEvent("onkeydown", boundKeydownHandler); document.attachEvent("onkeyup", boundKeyupHandler); } fillGrid.call(this); storageData = storage.read(this.options.storagePrefix + this.options.id); // TODO: Improve storage and state management if(storageData) { if(storageData.gridNumber) { this.overlay.classList.remove(this.options.classPrefix + this.state.gridNumber); this.overlay.classList.add(this.options.classPrefix + storageData.gridNumber); this.state.gridNumber = storageData.gridNumber; } if(storageData.overlayHold) { this.overlay.style.display = "block"; this.state.overlayOn = true; this.state.overlayHold = true; } if(storageData.overlayZIndex) { if(storageData.overlayZIndex === "B"){ this.overlay.style.zIndex = this.options.overlayZBG; } else if(storageData.overlayZIndex === "F"){ this.overlay.style.zIndex = this.options.overlayZFG; } this.state.overlayZIndex = storageData.overlayZIndex; } } }; Hashgrid.prototype.showOverlay = function() { this.overlay.style.display = "block"; this.state.overlayOn = true; }; Hashgrid.prototype.hideOverlay = function() { this.overlay.style.display = "none"; this.state.overlayOn = false; }; Hashgrid.prototype.destroy = function() { // Remove grid container this.overlay.remove(); // Remove storage data storage.remove(this.options.storagePrefix + this.options.id); // Remove keyboard events listener if(document.removeEventListener) { document.removeEventListener("keydown", boundKeydownHandler); document.removeEventListener("keyup", boundKeyupHandler); } else if(document.detachevent){ document.detachEvent("onkeydown", boundKeydownHandler); document.detachEvent("onkeyup", boundKeyupHandler); } }; // Private helper functions fillGrid = function() { var columnContainer = document.createElement("div"), column = document.createElement("div"), columnCount = 0, columnWidth, docFragment = document.createDocumentFragment(), options = this.options, overlay = this.overlay, overlayHeight, overlayWidth, rowContainer = document.createElement("div"), row = document.createElement("div"), rowCount = 0, rowHeight; // Row and column container rowContainer.classList.add(options.id + "-row-container"); columnContainer.classList.add(options.id + "-column-container"); overlay.appendChild(rowContainer); overlay.appendChild(columnContainer); // First row and column row.classList.add(options.id + "__row"); column.classList.add(options.id + "__column"); rowContainer.appendChild(row); columnContainer.appendChild(column); // Display temporarily to get row and column size overlay.style.display = "block"; overlay.top = "-9999px"; overlayHeight = overlay.scrollHeight; overlayWidth = overlay.scrollWidth; rowHeight = row.getBoundingClientRect().height; // height + border columnWidth = column.clientWidth; // Hide it again overlay.style.display = "none"; overlay.top = "0"; if(!rowHeight && !columnWidth) { return false; } if(rowHeight) { // Calculate rows needed rowCount = Math.floor(overlayHeight / rowHeight) - 1; // Fill the rows while(rowCount--) { row = document.createElement("div"); row.classList.add(options.id + "__row"); docFragment.appendChild(row); } rowContainer.appendChild(docFragment); } else { rowContainer.remove(row); } if(columnWidth) { // Calculate columns needed columnCount = Math.floor(overlayWidth / columnWidth) - 2; // Fill the columns while(columnCount--) { column = document.createElement("div"); column.classList.add(options.id + "__column"); docFragment.appendChild(column); } columnContainer.appendChild(docFragment); } else { columnContainer.remove(column); } }; keydownHandler = function(event) { var k, m, options = this.options, state = this.state, source = event.target.tagName.toLowerCase(); - if ((source == 'input') || (source == 'textarea') || (source == 'select')) { + if ((source == "input") || (source == "textarea") || (source == "select")) { return true; } m = Helper.getKeyModifier(event, options.modifierKey); if(!m) { return true; } k = Helper.getKey(event); if(!k) { return true; } if(state.isKeyDown[k]) { return true; } state.isKeyDown[k] = true; switch(k) { - case options.showGridKey: - if(!state.overlayOn) { - this.showOverlay(); - state.overlayOn = true; - } - else if(state.overlayHold) { - this.hideOverlay(); - state.overlayOn = false; - state.overlayHold = false; + case options.showGridKey: + if(!state.overlayOn) { + this.showOverlay(); + state.overlayOn = true; + } + else if(state.overlayHold) { + this.hideOverlay(); + state.overlayOn = false; + state.overlayHold = false; - storage.write(options.storagePrefix + options.id, createStorageData.call(this)); - } - break; - case options.holdGridKey: - if(state.overlayOn && !state.overlayHold) { - state.overlayHold = true; + storage.write(options.storagePrefix + options.id, createStorageData.call(this)); + } + break; + case options.holdGridKey: + if(state.overlayOn && !state.overlayHold) { + state.overlayHold = true; - storage.write(options.storagePrefix + options.id, createStorageData.call(this)); + storage.write(options.storagePrefix + options.id, createStorageData.call(this)); + } + break; + case options.foregroundKey: + // TODO: Turn into instance method + if(state.overlayOn) { + if(this.overlay.style.zIndex === options.overlayZFG) { + this.overlay.style.zIndex = options.overlayZBG; + state.overlayZIndex = "B"; + } + else { + this.overlay.style.zIndex = options.overlayZFG; + state.overlayZIndex = "F"; } - break; - case options.foregroundKey: - // TODO: Turn into instance method - if(state.overlayOn) { - if(this.overlay.style.zIndex === options.overlayZFG) { - this.overlay.style.zIndex = options.overlayZBG; - state.overlayZIndex = "B"; - } - else { - this.overlay.style.zIndex = options.overlayZFG; - state.overlayZIndex = "F"; - } - - storage.write(options.storagePrefix + options.id, createStorageData.call(this)); + + storage.write(options.storagePrefix + options.id, createStorageData.call(this)); + } + break; + case options.jumpGridsKey: + // TODO: Turn into instance method + if(state.overlayOn && options.numberOfGrids > 1) { + // Cycle through available grids + this.overlay.classList.remove(options.classPrefix + state.gridNumber); + state.gridNumber += 1; + + if(state.gridNumber > options.numberOfGrids) { + state.gridNumber = 1; } - break; - case options.jumpGridsKey: - // TODO: Turn into instance method - if(state.overlayOn && options.numberOfGrids > 1) { - // Cycle through available grids - this.overlay.classList.remove(options.classPrefix + state.gridNumber); - state.gridNumber += 1; - - if(state.gridNumber > options.numberOfGrids) { - state.gridNumber = 1; - } - - this.overlay.classList.add(options.classPrefix + state.gridNumber); - this.showOverlay(); - - if (/webkit/.test( navigator.userAgent.toLowerCase() )) { - Helper.forceRepaint(); - } - - storage.write(options.storagePrefix + options.id, createStorageData.call(this)); + + this.overlay.classList.add(options.classPrefix + state.gridNumber); + this.showOverlay(); + + if (/webkit/.test( navigator.userAgent.toLowerCase() )) { + Helper.forceRepaint(); } - break; + + storage.write(options.storagePrefix + options.id, createStorageData.call(this)); + } + break; } return true; }; keyupHandler = function(event) { var k, m = Helper.getKeyModifier(event), options = this.options, state = this.state; if (!m) { return true; } k = Helper.getKey(event); delete state.isKeyDown[k]; if (k && (k == options.showGridKey) && !state.overlayHold) { this.hideOverlay(); state.overlayOn = false; } return true; }; createStorageData = function() { var state = this.state; return { gridNumber: state.gridNumber, overlayHold: state.overlayHold, overlayZIndex: state.overlayZIndex }; }; return Hashgrid; })(); window.Hashgrid = Hashgrid; // REMOVE START // if (typeof module!="undefined" && module.exports) module.exports = Hashgrid; // REMOVE END // diff --git a/src/helper.js b/src/helper.js index 2f0b95a..216e503 100644 --- a/src/helper.js +++ b/src/helper.js @@ -1,97 +1,99 @@ var Helper = (function() { "use strict"; function copyObjectProperties(target, source) { var properties = Object.getOwnPropertyNames(source); var propertyLength = properties.length; var idx; for(idx = 0; idx < propertyLength; idx++) { target[properties[idx]] = source[properties[idx]]; } } return { /* Keyboard event helpers */ getKey: function(event) { var k = false, c = (event.keyCode ? event.keyCode : event.which); // Handle keywords - if (c == 13) k = 'enter'; + if (c == 13) k = "enter"; // Handle letters else k = String.fromCharCode(c).toLowerCase(); return k; }, getKeyModifier: function(event, modifierOption) { if (modifierOption === null) return true; // Bypass by default var m = true; switch(modifierOption) { - case 'ctrl': - m = (event.ctrlKey ? event.ctrlKey : false); + case "ctrl": + m = (event.ctrlKey ? event.ctrlKey : false); break; - case 'alt': - m = (event.altKey ? event.altKey : false); + case "alt": + m = (event.altKey ? event.altKey : false); break; - case 'shift': - m = (event.shiftKey ? event.shiftKey : false); + case "shift": + m = (event.shiftKey ? event.shiftKey : false); break; } return m; }, /* * Simple object merge * - merge obj1 and obj2 to mergedResult * - mergedResult, obj1 and obj2 can only contain primitives * - obj2 is optional */ mergeObjects: function(mergedObject, obj1, obj2) { if(!mergedObject && !obj1 && !obj2) { return {}; } else if( (mergedObject && typeof(mergedObject) !== "object") || (obj1 && typeof(obj1) !== "object") || (obj2 && typeof(obj2) !== "object")) { return {}; } if(obj1) { copyObjectProperties(mergedObject, obj1); } if(obj2) { copyObjectProperties(mergedObject, obj2); } return mergedObject; }, /** * Forces a repaint (because WebKit has issues) * http://www.sitepoint.com/forums/showthread.php?p=4538763 * http://www.phpied.com/the-new-game-show-will-it-reflow/ */ forceRepaint: function() { var ss = document.styleSheets[0]; try { - ss.addRule('.xxxxxx', 'position: relative'); + ss.addRule(".xxxxxx", "position: relative"); ss.removeRule(ss.rules.length - 1); } - catch(e) {} + catch(e) { + return; + } } }; })(); // REMOVE START // if (typeof module!="undefined" && module.exports) module.exports = Helper; // REMOVE END // diff --git a/src/sessionStorage.js b/src/sessionStorage.js index 5aace31..d2875b4 100644 --- a/src/sessionStorage.js +++ b/src/sessionStorage.js @@ -1,42 +1,42 @@ var SessionStorage = (function() { "use strict"; function SessionStorage() { this.storage = window.sessionStorage; } - SessionStorage.prototype.read = function(dataLabel) { - var dataValue = this.storage.getItem(dataLabel); - - if(dataValue) { - return JSON.parse(dataValue); - } - else { - return null; - } - }; - - SessionStorage.prototype.write = function(dataLabel, dataValue) { - this.storage.setItem(dataLabel, JSON.stringify(dataValue)); - return dataValue; - }; - - SessionStorage.prototype.remove = function(dataLabel) { - var removedDataValue = this.read(dataLabel); - - if(removedDataValue) { - this.storage.removeItem(dataLabel); - return removedDataValue; - } - else { - return null; - } - }; - return SessionStorage; })(); +SessionStorage.prototype.read = function(dataLabel) { + var dataValue = this.storage.getItem(dataLabel); + + if(dataValue) { + return JSON.parse(dataValue); + } + else { + return null; + } +}; + +SessionStorage.prototype.write = function(dataLabel, dataValue) { + this.storage.setItem(dataLabel, JSON.stringify(dataValue)); + return dataValue; +}; + +SessionStorage.prototype.remove = function(dataLabel) { + var removedDataValue = this.read(dataLabel); + + if(removedDataValue) { + this.storage.removeItem(dataLabel); + return removedDataValue; + } + else { + return null; + } +}; + // REMOVE START // if (typeof module!="undefined" && module.exports) module.exports = SessionStorage; // REMOVE END // diff --git a/src/storage.js b/src/storage.js index 16169c4..1c3b367 100644 --- a/src/storage.js +++ b/src/storage.js @@ -1,45 +1,45 @@ /* * This is just a proxy for storage function - * Ideally, local storage is used, + * Ideally, session storage is used, * cookie storage is provided only as fallback */ // REMOVE START // -if (typeof module!='undefined' && module.exports) { +if (typeof module != "undefined" && module.exports) { var SessionStorage = require("./sessionStorage"); var CookieStorage = require("./cookieStorage"); } // REMOVE END // -var Storage = (function() { +var SimpleStorage = (function() { "use strict"; - function Storage() { + function SimpleStorage() { if(this.hasSessionStorage()) { return new SessionStorage(); } else { return new CookieStorage(); } } - Storage.prototype.hasSessionStorage = function() { - try { - var storage = window.sessionStorage, - someData = "some value"; + return SimpleStorage; +})(); - storage.setItem(someData, someData); - storage.removeItem(someData); - return true; - } - catch(e) { - return false; - } - }; +SimpleStorage.prototype.hasSessionStorage = function() { + try { + var storage = window.sessionStorage, + someData = "some value"; - return Storage; -})(); + storage.setItem(someData, someData); + storage.removeItem(someData); + return true; + } + catch(e) { + return false; + } +}; // REMOVE START // -if (typeof module!="undefined" && module.exports) module.exports = Storage; +if (typeof module!="undefined" && module.exports) module.exports = SimpleStorage; // REMOVE END //
dotjay/hashgrid
d953c09ea3fa85e18deef5a9a681cea1fc3282ae
Improve grid column and row insertion
diff --git a/dist/javascripts/hashgrid.js b/dist/javascripts/hashgrid.js index 56c800e..fc857e5 100644 --- a/dist/javascripts/hashgrid.js +++ b/dist/javascripts/hashgrid.js @@ -1,366 +1,374 @@ (function(window, document) { var Helper = function() { "use strict"; function copyObjectProperties(target, source) { var properties = Object.getOwnPropertyNames(source); var propertyLength = properties.length; var idx; for (idx = 0; idx < propertyLength; idx++) { target[properties[idx]] = source[properties[idx]]; } } return { getKey: function(event) { var k = false, c = event.keyCode ? event.keyCode : event.which; if (c == 13) k = "enter"; else k = String.fromCharCode(c).toLowerCase(); return k; }, getKeyModifier: function(event, modifierOption) { if (modifierOption === null) return true; var m = true; switch (modifierOption) { case "ctrl": m = event.ctrlKey ? event.ctrlKey : false; break; case "alt": m = event.altKey ? event.altKey : false; break; case "shift": m = event.shiftKey ? event.shiftKey : false; break; } return m; }, mergeObjects: function(mergedObject, obj1, obj2) { if (!mergedObject && !obj1 && !obj2) { return {}; } else if (mergedObject && typeof mergedObject !== "object" || obj1 && typeof obj1 !== "object" || obj2 && typeof obj2 !== "object") { return {}; } if (obj1) { copyObjectProperties(mergedObject, obj1); } if (obj2) { copyObjectProperties(mergedObject, obj2); } return mergedObject; }, forceRepaint: function() { var ss = document.styleSheets[0]; try { ss.addRule(".xxxxxx", "position: relative"); ss.removeRule(ss.rules.length - 1); } catch (e) {} } }; }(); var CookieStorage = function() { "use strict"; function CookieStorage() {} CookieStorage.prototype.read = function(cookieLabel) { var cookieCrumb, cookieArray = document.cookie.split(";"), i = 0, cookieCrumbCount = cookieArray.length; cookieLabel = cookieLabel + "="; for (;i < cookieCrumbCount; i++) { cookieCrumb = cookieArray[i]; while (cookieCrumb.charAt(0) === " ") { cookieCrumb = cookieCrumb.substring(1, cookieCrumb.length); } if (cookieCrumb.indexOf(cookieLabel) === 0) { return JSON.parse(cookieCrumb.substring(cookieLabel.length, cookieCrumb.length)); } } return null; }; CookieStorage.prototype.write = function(cookieLabel, cookieValue, expirationDay) { var date, cookieExpires = "", toBeWritten = ""; if (expirationDay) { date = new Date(); date.setTime(date.getTime() + expirationDay * 24 * 60 * 60 * 1e3); cookieExpires = "; expires=" + date.toGMTString(); } toBeWritten = cookieLabel + "=" + JSON.stringify(cookieValue) + cookieExpires + "; path=/"; document.cookie = toBeWritten; return toBeWritten; }; CookieStorage.prototype.remove = function(cookieLabel) { var removedCookieValue = this.read(cookieLabel); if (removedCookieValue) { this.write(cookieLabel, "", -1); return removedCookieValue; } else { return null; } }; return CookieStorage; }(); var SessionStorage = function() { "use strict"; function SessionStorage() { this.storage = window.sessionStorage; } SessionStorage.prototype.read = function(dataLabel) { var dataValue = this.storage.getItem(dataLabel); if (dataValue) { return JSON.parse(dataValue); } else { return null; } }; SessionStorage.prototype.write = function(dataLabel, dataValue) { this.storage.setItem(dataLabel, JSON.stringify(dataValue)); return dataValue; }; SessionStorage.prototype.remove = function(dataLabel) { var removedDataValue = this.read(dataLabel); if (removedDataValue) { this.storage.removeItem(dataLabel); return removedDataValue; } else { return null; } }; return SessionStorage; }(); var Storage = function() { "use strict"; function Storage() { if (this.hasSessionStorage()) { return new SessionStorage(); } else { return new CookieStorage(); } } Storage.prototype.hasSessionStorage = function() { try { var storage = window.sessionStorage, someData = "some value"; storage.setItem(someData, someData); storage.removeItem(someData); return true; } catch (e) { return false; } }; return Storage; }(); var Hashgrid = function() { "use strict"; var storage = new Storage(), fillGrid, boundKeydownHandler, keydownHandler, boundKeyupHandler, keyupHandler, createStorageData; function Hashgrid(customOptions) { var defaultOptions = { id: "hashgrid", modifierKey: null, showGridKey: "g", holdGridKey: "h", foregroundKey: "f", jumpGridsKey: "j", numberOfGrids: 1, classPrefix: "hashgrid", storagePrefix: "hashgrid" }, privateOptions = { overlayZBG: "-1", overlayZFG: "9999" }; this.options = Helper.mergeObjects(defaultOptions, customOptions, privateOptions); this.state = { overlayHold: false, overlayOn: false, overlayZIndex: "B", isKeyDown: {}, gridNumber: 1 }; this.init(); } Hashgrid.prototype.init = function() { var storageData; this.overlay = document.createElement("div"); this.overlay.id = this.options.id; this.overlay.classList.add(this.options.classPrefix + this.state.gridNumber); this.overlay.style.display = "none"; this.overlay.style.pointerEvents = "none"; this.overlay.style.height = document.body.scrollHeight + "px"; if (this.overlay.style.zIndex === "auto") { this.overlay.style.zIndex = this.overlayZBackground; } document.body.insertBefore(this.overlay, document.body.firstChild); boundKeydownHandler = keydownHandler.bind(this); boundKeyupHandler = keyupHandler.bind(this); if (document.addEventListener) { document.addEventListener("keydown", boundKeydownHandler, false); document.addEventListener("keyup", boundKeyupHandler, false); } else if (document.attachEvent) { document.attachEvent("onkeydown", boundKeydownHandler); document.attachEvent("onkeyup", boundKeyupHandler); } fillGrid.call(this); storageData = storage.read(this.options.storagePrefix + this.options.id); if (storageData) { if (storageData.gridNumber) { this.overlay.classList.remove(this.options.classPrefix + this.state.gridNumber); this.overlay.classList.add(this.options.classPrefix + storageData.gridNumber); this.state.gridNumber = storageData.gridNumber; } if (storageData.overlayHold) { this.overlay.style.display = "block"; this.state.overlayOn = true; this.state.overlayHold = true; } if (storageData.overlayZIndex) { if (storageData.overlayZIndex === "B") { this.overlay.style.zIndex = this.options.overlayZBG; } else if (storageData.overlayZIndex === "F") { this.overlay.style.zIndex = this.options.overlayZFG; } this.state.overlayZIndex = storageData.overlayZIndex; } } }; Hashgrid.prototype.showOverlay = function() { this.overlay.style.display = "block"; this.state.overlayOn = true; }; Hashgrid.prototype.hideOverlay = function() { this.overlay.style.display = "none"; this.state.overlayOn = false; }; Hashgrid.prototype.destroy = function() { this.overlay.remove(); storage.remove(this.options.storagePrefix + this.options.id); if (document.removeEventListener) { document.removeEventListener("keydown", boundKeydownHandler); document.removeEventListener("keyup", boundKeyupHandler); } else if (document.detachevent) { document.detachEvent("onkeydown", boundKeydownHandler); document.detachEvent("onkeyup", boundKeyupHandler); } }; fillGrid = function() { - var columnContainer = document.createElement("div"), column = document.createElement("div"), columnCount, columnWidth, docFragment = document.createDocumentFragment(), options = this.options, overlay = this.overlay, overlayHeight, overlayWidth, rowContainer = document.createElement("div"), row = document.createElement("div"), rowCount, rowHeight; + var columnContainer = document.createElement("div"), column = document.createElement("div"), columnCount = 0, columnWidth, docFragment = document.createDocumentFragment(), options = this.options, overlay = this.overlay, overlayHeight, overlayWidth, rowContainer = document.createElement("div"), row = document.createElement("div"), rowCount = 0, rowHeight; rowContainer.classList.add(options.id + "-row-container"); columnContainer.classList.add(options.id + "-column-container"); overlay.appendChild(rowContainer); overlay.appendChild(columnContainer); row.classList.add(options.id + "__row"); column.classList.add(options.id + "__column"); rowContainer.appendChild(row); columnContainer.appendChild(column); overlay.style.display = "block"; overlay.top = "-9999px"; overlayHeight = overlay.scrollHeight; overlayWidth = overlay.scrollWidth; rowHeight = row.getBoundingClientRect().height; columnWidth = column.clientWidth; overlay.style.display = "none"; overlay.top = "0"; - if (!rowHeight || !columnWidth) { + if (!rowHeight && !columnWidth) { return false; } - rowCount = Math.floor(overlayHeight / rowHeight) - 1; - columnCount = Math.floor(overlayWidth / columnWidth) - 2; - while (rowCount--) { - row = document.createElement("div"); - row.classList.add(options.id + "__row"); - docFragment.appendChild(row); + if (rowHeight) { + rowCount = Math.floor(overlayHeight / rowHeight) - 1; + while (rowCount--) { + row = document.createElement("div"); + row.classList.add(options.id + "__row"); + docFragment.appendChild(row); + } + rowContainer.appendChild(docFragment); + } else { + rowContainer.remove(row); } - rowContainer.appendChild(docFragment); - while (columnCount--) { - column = document.createElement("div"); - column.classList.add(options.id + "__column"); - docFragment.appendChild(column); + if (columnWidth) { + columnCount = Math.floor(overlayWidth / columnWidth) - 2; + while (columnCount--) { + column = document.createElement("div"); + column.classList.add(options.id + "__column"); + docFragment.appendChild(column); + } + columnContainer.appendChild(docFragment); + } else { + columnContainer.remove(column); } - columnContainer.appendChild(docFragment); }; keydownHandler = function(event) { var k, m, options = this.options, state = this.state, source = event.target.tagName.toLowerCase(); if (source == "input" || source == "textarea" || source == "select") { return true; } m = Helper.getKeyModifier(event, options.modifierKey); if (!m) { return true; } k = Helper.getKey(event); if (!k) { return true; } if (state.isKeyDown[k]) { return true; } state.isKeyDown[k] = true; switch (k) { case options.showGridKey: if (!state.overlayOn) { this.showOverlay(); state.overlayOn = true; } else if (state.overlayHold) { this.hideOverlay(); state.overlayOn = false; state.overlayHold = false; storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; case options.holdGridKey: if (state.overlayOn && !state.overlayHold) { state.overlayHold = true; storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; case options.foregroundKey: if (state.overlayOn) { if (this.overlay.style.zIndex === options.overlayZFG) { this.overlay.style.zIndex = options.overlayZBG; state.overlayZIndex = "B"; } else { this.overlay.style.zIndex = options.overlayZFG; state.overlayZIndex = "F"; } storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; case options.jumpGridsKey: if (state.overlayOn && options.numberOfGrids > 1) { this.overlay.classList.remove(options.classPrefix + state.gridNumber); state.gridNumber += 1; if (state.gridNumber > options.numberOfGrids) { state.gridNumber = 1; } this.overlay.classList.add(options.classPrefix + state.gridNumber); this.showOverlay(); if (/webkit/.test(navigator.userAgent.toLowerCase())) { Helper.forceRepaint(); } storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; } return true; }; keyupHandler = function(event) { var k, m = Helper.getKeyModifier(event), options = this.options, state = this.state; if (!m) { return true; } k = Helper.getKey(event); delete state.isKeyDown[k]; if (k && k == options.showGridKey && !state.overlayHold) { this.hideOverlay(); state.overlayOn = false; } return true; }; createStorageData = function() { var state = this.state; return { gridNumber: state.gridNumber, overlayHold: state.overlayHold, overlayZIndex: state.overlayZIndex }; }; return Hashgrid; }(); window.Hashgrid = Hashgrid; })(window, document); \ No newline at end of file diff --git a/dist/javascripts/hashgrid.min.js b/dist/javascripts/hashgrid.min.js index ae8708a..2eebfc3 100644 --- a/dist/javascripts/hashgrid.min.js +++ b/dist/javascripts/hashgrid.min.js @@ -1 +1 @@ -!function(a,b){var c=function(){"use strict";function a(a,b){var c,d=Object.getOwnPropertyNames(b),e=d.length;for(c=0;e>c;c++)a[d[c]]=b[d[c]]}return{getKey:function(a){var b=!1,c=a.keyCode?a.keyCode:a.which;return b=13==c?"enter":String.fromCharCode(c).toLowerCase()},getKeyModifier:function(a,b){if(null===b)return!0;var c=!0;switch(b){case"ctrl":c=a.ctrlKey?a.ctrlKey:!1;break;case"alt":c=a.altKey?a.altKey:!1;break;case"shift":c=a.shiftKey?a.shiftKey:!1}return c},mergeObjects:function(b,c,d){return b||c||d?b&&"object"!=typeof b||c&&"object"!=typeof c||d&&"object"!=typeof d?{}:(c&&a(b,c),d&&a(b,d),b):{}},forceRepaint:function(){var a=b.styleSheets[0];try{a.addRule(".xxxxxx","position: relative"),a.removeRule(a.rules.length-1)}catch(c){}}}}(),d=function(){"use strict";function a(){}return a.prototype.read=function(a){var c,d=b.cookie.split(";"),e=0,f=d.length;for(a+="=";f>e;e++){for(c=d[e];" "===c.charAt(0);)c=c.substring(1,c.length);if(0===c.indexOf(a))return JSON.parse(c.substring(a.length,c.length))}return null},a.prototype.write=function(a,c,d){var e,f="",g="";return d&&(e=new Date,e.setTime(e.getTime()+24*d*60*60*1e3),f="; expires="+e.toGMTString()),g=a+"="+JSON.stringify(c)+f+"; path=/",b.cookie=g,g},a.prototype.remove=function(a){var b=this.read(a);return b?(this.write(a,"",-1),b):null},a}(),e=function(){"use strict";function b(){this.storage=a.sessionStorage}return b.prototype.read=function(a){var b=this.storage.getItem(a);return b?JSON.parse(b):null},b.prototype.write=function(a,b){return this.storage.setItem(a,JSON.stringify(b)),b},b.prototype.remove=function(a){var b=this.read(a);return b?(this.storage.removeItem(a),b):null},b}(),f=function(){"use strict";function b(){return this.hasSessionStorage()?new e:new d}return b.prototype.hasSessionStorage=function(){try{var b=a.sessionStorage,c="some value";return b.setItem(c,c),b.removeItem(c),!0}catch(d){return!1}},b}(),g=function(){"use strict";function a(a){var b={id:"hashgrid",modifierKey:null,showGridKey:"g",holdGridKey:"h",foregroundKey:"f",jumpGridsKey:"j",numberOfGrids:1,classPrefix:"hashgrid",storagePrefix:"hashgrid"},d={overlayZBG:"-1",overlayZFG:"9999"};this.options=c.mergeObjects(b,a,d),this.state={overlayHold:!1,overlayOn:!1,overlayZIndex:"B",isKeyDown:{},gridNumber:1},this.init()}var d,e,g,h,i,j,k=new f;return a.prototype.init=function(){var a;this.overlay=b.createElement("div"),this.overlay.id=this.options.id,this.overlay.classList.add(this.options.classPrefix+this.state.gridNumber),this.overlay.style.display="none",this.overlay.style.pointerEvents="none",this.overlay.style.height=b.body.scrollHeight+"px","auto"===this.overlay.style.zIndex&&(this.overlay.style.zIndex=this.overlayZBackground),b.body.insertBefore(this.overlay,b.body.firstChild),e=g.bind(this),h=i.bind(this),b.addEventListener?(b.addEventListener("keydown",e,!1),b.addEventListener("keyup",h,!1)):b.attachEvent&&(b.attachEvent("onkeydown",e),b.attachEvent("onkeyup",h)),d.call(this),a=k.read(this.options.storagePrefix+this.options.id),a&&(a.gridNumber&&(this.overlay.classList.remove(this.options.classPrefix+this.state.gridNumber),this.overlay.classList.add(this.options.classPrefix+a.gridNumber),this.state.gridNumber=a.gridNumber),a.overlayHold&&(this.overlay.style.display="block",this.state.overlayOn=!0,this.state.overlayHold=!0),a.overlayZIndex&&("B"===a.overlayZIndex?this.overlay.style.zIndex=this.options.overlayZBG:"F"===a.overlayZIndex&&(this.overlay.style.zIndex=this.options.overlayZFG),this.state.overlayZIndex=a.overlayZIndex))},a.prototype.showOverlay=function(){this.overlay.style.display="block",this.state.overlayOn=!0},a.prototype.hideOverlay=function(){this.overlay.style.display="none",this.state.overlayOn=!1},a.prototype.destroy=function(){this.overlay.remove(),k.remove(this.options.storagePrefix+this.options.id),b.removeEventListener?(b.removeEventListener("keydown",e),b.removeEventListener("keyup",h)):b.detachevent&&(b.detachEvent("onkeydown",e),b.detachEvent("onkeyup",h))},d=function(){var a,c,d,e,f,g,h=b.createElement("div"),i=b.createElement("div"),j=b.createDocumentFragment(),k=this.options,l=this.overlay,m=b.createElement("div"),n=b.createElement("div");if(m.classList.add(k.id+"-row-container"),h.classList.add(k.id+"-column-container"),l.appendChild(m),l.appendChild(h),n.classList.add(k.id+"__row"),i.classList.add(k.id+"__column"),m.appendChild(n),h.appendChild(i),l.style.display="block",l.top="-9999px",d=l.scrollHeight,e=l.scrollWidth,g=n.getBoundingClientRect().height,c=i.clientWidth,l.style.display="none",l.top="0",!g||!c)return!1;for(f=Math.floor(d/g)-1,a=Math.floor(e/c)-2;f--;)n=b.createElement("div"),n.classList.add(k.id+"__row"),j.appendChild(n);for(m.appendChild(j);a--;)i=b.createElement("div"),i.classList.add(k.id+"__column"),j.appendChild(i);h.appendChild(j)},g=function(a){var b,d,e=this.options,f=this.state,g=a.target.tagName.toLowerCase();if("input"==g||"textarea"==g||"select"==g)return!0;if(d=c.getKeyModifier(a,e.modifierKey),!d)return!0;if(b=c.getKey(a),!b)return!0;if(f.isKeyDown[b])return!0;switch(f.isKeyDown[b]=!0,b){case e.showGridKey:f.overlayOn?f.overlayHold&&(this.hideOverlay(),f.overlayOn=!1,f.overlayHold=!1,k.write(e.storagePrefix+e.id,j.call(this))):(this.showOverlay(),f.overlayOn=!0);break;case e.holdGridKey:f.overlayOn&&!f.overlayHold&&(f.overlayHold=!0,k.write(e.storagePrefix+e.id,j.call(this)));break;case e.foregroundKey:f.overlayOn&&(this.overlay.style.zIndex===e.overlayZFG?(this.overlay.style.zIndex=e.overlayZBG,f.overlayZIndex="B"):(this.overlay.style.zIndex=e.overlayZFG,f.overlayZIndex="F"),k.write(e.storagePrefix+e.id,j.call(this)));break;case e.jumpGridsKey:f.overlayOn&&e.numberOfGrids>1&&(this.overlay.classList.remove(e.classPrefix+f.gridNumber),f.gridNumber+=1,f.gridNumber>e.numberOfGrids&&(f.gridNumber=1),this.overlay.classList.add(e.classPrefix+f.gridNumber),this.showOverlay(),/webkit/.test(navigator.userAgent.toLowerCase())&&c.forceRepaint(),k.write(e.storagePrefix+e.id,j.call(this)))}return!0},i=function(a){var b,d=c.getKeyModifier(a),e=this.options,f=this.state;return d?(b=c.getKey(a),delete f.isKeyDown[b],b&&b==e.showGridKey&&!f.overlayHold&&(this.hideOverlay(),f.overlayOn=!1),!0):!0},j=function(){var a=this.state;return{gridNumber:a.gridNumber,overlayHold:a.overlayHold,overlayZIndex:a.overlayZIndex}},a}();a.Hashgrid=g}(window,document); \ No newline at end of file +!function(a,b){var c=function(){"use strict";function a(a,b){var c,d=Object.getOwnPropertyNames(b),e=d.length;for(c=0;e>c;c++)a[d[c]]=b[d[c]]}return{getKey:function(a){var b=!1,c=a.keyCode?a.keyCode:a.which;return b=13==c?"enter":String.fromCharCode(c).toLowerCase()},getKeyModifier:function(a,b){if(null===b)return!0;var c=!0;switch(b){case"ctrl":c=a.ctrlKey?a.ctrlKey:!1;break;case"alt":c=a.altKey?a.altKey:!1;break;case"shift":c=a.shiftKey?a.shiftKey:!1}return c},mergeObjects:function(b,c,d){return b||c||d?b&&"object"!=typeof b||c&&"object"!=typeof c||d&&"object"!=typeof d?{}:(c&&a(b,c),d&&a(b,d),b):{}},forceRepaint:function(){var a=b.styleSheets[0];try{a.addRule(".xxxxxx","position: relative"),a.removeRule(a.rules.length-1)}catch(c){}}}}(),d=function(){"use strict";function a(){}return a.prototype.read=function(a){var c,d=b.cookie.split(";"),e=0,f=d.length;for(a+="=";f>e;e++){for(c=d[e];" "===c.charAt(0);)c=c.substring(1,c.length);if(0===c.indexOf(a))return JSON.parse(c.substring(a.length,c.length))}return null},a.prototype.write=function(a,c,d){var e,f="",g="";return d&&(e=new Date,e.setTime(e.getTime()+24*d*60*60*1e3),f="; expires="+e.toGMTString()),g=a+"="+JSON.stringify(c)+f+"; path=/",b.cookie=g,g},a.prototype.remove=function(a){var b=this.read(a);return b?(this.write(a,"",-1),b):null},a}(),e=function(){"use strict";function b(){this.storage=a.sessionStorage}return b.prototype.read=function(a){var b=this.storage.getItem(a);return b?JSON.parse(b):null},b.prototype.write=function(a,b){return this.storage.setItem(a,JSON.stringify(b)),b},b.prototype.remove=function(a){var b=this.read(a);return b?(this.storage.removeItem(a),b):null},b}(),f=function(){"use strict";function b(){return this.hasSessionStorage()?new e:new d}return b.prototype.hasSessionStorage=function(){try{var b=a.sessionStorage,c="some value";return b.setItem(c,c),b.removeItem(c),!0}catch(d){return!1}},b}(),g=function(){"use strict";function a(a){var b={id:"hashgrid",modifierKey:null,showGridKey:"g",holdGridKey:"h",foregroundKey:"f",jumpGridsKey:"j",numberOfGrids:1,classPrefix:"hashgrid",storagePrefix:"hashgrid"},d={overlayZBG:"-1",overlayZFG:"9999"};this.options=c.mergeObjects(b,a,d),this.state={overlayHold:!1,overlayOn:!1,overlayZIndex:"B",isKeyDown:{},gridNumber:1},this.init()}var d,e,g,h,i,j,k=new f;return a.prototype.init=function(){var a;this.overlay=b.createElement("div"),this.overlay.id=this.options.id,this.overlay.classList.add(this.options.classPrefix+this.state.gridNumber),this.overlay.style.display="none",this.overlay.style.pointerEvents="none",this.overlay.style.height=b.body.scrollHeight+"px","auto"===this.overlay.style.zIndex&&(this.overlay.style.zIndex=this.overlayZBackground),b.body.insertBefore(this.overlay,b.body.firstChild),e=g.bind(this),h=i.bind(this),b.addEventListener?(b.addEventListener("keydown",e,!1),b.addEventListener("keyup",h,!1)):b.attachEvent&&(b.attachEvent("onkeydown",e),b.attachEvent("onkeyup",h)),d.call(this),a=k.read(this.options.storagePrefix+this.options.id),a&&(a.gridNumber&&(this.overlay.classList.remove(this.options.classPrefix+this.state.gridNumber),this.overlay.classList.add(this.options.classPrefix+a.gridNumber),this.state.gridNumber=a.gridNumber),a.overlayHold&&(this.overlay.style.display="block",this.state.overlayOn=!0,this.state.overlayHold=!0),a.overlayZIndex&&("B"===a.overlayZIndex?this.overlay.style.zIndex=this.options.overlayZBG:"F"===a.overlayZIndex&&(this.overlay.style.zIndex=this.options.overlayZFG),this.state.overlayZIndex=a.overlayZIndex))},a.prototype.showOverlay=function(){this.overlay.style.display="block",this.state.overlayOn=!0},a.prototype.hideOverlay=function(){this.overlay.style.display="none",this.state.overlayOn=!1},a.prototype.destroy=function(){this.overlay.remove(),k.remove(this.options.storagePrefix+this.options.id),b.removeEventListener?(b.removeEventListener("keydown",e),b.removeEventListener("keyup",h)):b.detachevent&&(b.detachEvent("onkeydown",e),b.detachEvent("onkeyup",h))},d=function(){var a,c,d,e,f=b.createElement("div"),g=b.createElement("div"),h=0,i=b.createDocumentFragment(),j=this.options,k=this.overlay,l=b.createElement("div"),m=b.createElement("div"),n=0;if(l.classList.add(j.id+"-row-container"),f.classList.add(j.id+"-column-container"),k.appendChild(l),k.appendChild(f),m.classList.add(j.id+"__row"),g.classList.add(j.id+"__column"),l.appendChild(m),f.appendChild(g),k.style.display="block",k.top="-9999px",c=k.scrollHeight,d=k.scrollWidth,e=m.getBoundingClientRect().height,a=g.clientWidth,k.style.display="none",k.top="0",!e&&!a)return!1;if(e){for(n=Math.floor(c/e)-1;n--;)m=b.createElement("div"),m.classList.add(j.id+"__row"),i.appendChild(m);l.appendChild(i)}else l.remove(m);if(a){for(h=Math.floor(d/a)-2;h--;)g=b.createElement("div"),g.classList.add(j.id+"__column"),i.appendChild(g);f.appendChild(i)}else f.remove(g)},g=function(a){var b,d,e=this.options,f=this.state,g=a.target.tagName.toLowerCase();if("input"==g||"textarea"==g||"select"==g)return!0;if(d=c.getKeyModifier(a,e.modifierKey),!d)return!0;if(b=c.getKey(a),!b)return!0;if(f.isKeyDown[b])return!0;switch(f.isKeyDown[b]=!0,b){case e.showGridKey:f.overlayOn?f.overlayHold&&(this.hideOverlay(),f.overlayOn=!1,f.overlayHold=!1,k.write(e.storagePrefix+e.id,j.call(this))):(this.showOverlay(),f.overlayOn=!0);break;case e.holdGridKey:f.overlayOn&&!f.overlayHold&&(f.overlayHold=!0,k.write(e.storagePrefix+e.id,j.call(this)));break;case e.foregroundKey:f.overlayOn&&(this.overlay.style.zIndex===e.overlayZFG?(this.overlay.style.zIndex=e.overlayZBG,f.overlayZIndex="B"):(this.overlay.style.zIndex=e.overlayZFG,f.overlayZIndex="F"),k.write(e.storagePrefix+e.id,j.call(this)));break;case e.jumpGridsKey:f.overlayOn&&e.numberOfGrids>1&&(this.overlay.classList.remove(e.classPrefix+f.gridNumber),f.gridNumber+=1,f.gridNumber>e.numberOfGrids&&(f.gridNumber=1),this.overlay.classList.add(e.classPrefix+f.gridNumber),this.showOverlay(),/webkit/.test(navigator.userAgent.toLowerCase())&&c.forceRepaint(),k.write(e.storagePrefix+e.id,j.call(this)))}return!0},i=function(a){var b,d=c.getKeyModifier(a),e=this.options,f=this.state;return d?(b=c.getKey(a),delete f.isKeyDown[b],b&&b==e.showGridKey&&!f.overlayHold&&(this.hideOverlay(),f.overlayOn=!1),!0):!0},j=function(){var a=this.state;return{gridNumber:a.gridNumber,overlayHold:a.overlayHold,overlayZIndex:a.overlayZIndex}},a}();a.Hashgrid=g}(window,document); \ No newline at end of file diff --git a/src/hashgrid.js b/src/hashgrid.js index 57d2f45..06cdbff 100644 --- a/src/hashgrid.js +++ b/src/hashgrid.js @@ -1,390 +1,404 @@ /** * hashgrid (vanilla version) * http://github.com/dotjay/hashgrid * Version 10, 25 Nov 2015 * Written by Jon Gibbins at Analog, http://analog.coop/ * * Contibutors: * Sean Coates, http://seancoates.com/ * Phil Dokas, http://jetless.org/ * Andrew Jaswa, http://andrewjaswa.com/ * * License: * http://www.apache.org/licenses/LICENSE-2.0.html * * // Using a basic #grid setup * var grid = new Hashgrid(); * * // Using #grid with a custom id (e.g. #mygrid) * var grid = new Hashgrid("mygrid"); * * // Using #grid with additional options * var grid = new hashgrid({ * id: "mygrid", // id for the grid container * modifierKey: "alt", // optional "ctrl", "alt" or "shift" * showGridKey: "s", // key to show the grid * holdGridKey: "enter", // key to hold the grid shown * foregroundKey: "f", // key to toggle foreground/background * jumpGridsKey: "d", // key to cycle through the grids * numberOfGrids: 2, // number of grids * classPrefix: "mygrid", // prefix for rows and columns * storagePrefix: "mygrid" // prefix for storage label * }); */ // REMOVE START // if (typeof module!="undefined" && module.exports) { var Storage = require("./storage"); var Helper = require("./helper"); } // REMOVE END // var Hashgrid = (function() { "use strict"; var storage = new Storage(), fillGrid, boundKeydownHandler, keydownHandler, boundKeyupHandler, keyupHandler, createStorageData; // Constructor function Hashgrid(customOptions) { var defaultOptions = { id: "hashgrid", // id for the grid container modifierKey: null, // optional "ctrl", "alt" or "shift" showGridKey: "g", // key to show the grid holdGridKey: "h", // key to hold the grid shown foregroundKey: "f", // key to toggle foreground/background jumpGridsKey: "j", // key to cycle through the grids numberOfGrids: 1, // number of grids classPrefix: "hashgrid", // prefix for rows and columns storagePrefix: "hashgrid" // prefix for storage label }, privateOptions = { overlayZBG: "-1", overlayZFG: "9999" }; // Apply options this.options = Helper.mergeObjects(defaultOptions, customOptions, privateOptions); this.state = { overlayHold: false, overlayOn: false, overlayZIndex: "B", isKeyDown: {}, gridNumber: 1 }; this.init(); } // Instance methods Hashgrid.prototype.init = function() { var storageData; // Create overlay, hidden before adding to DOM this.overlay = document.createElement("div"); this.overlay.id = this.options.id; this.overlay.classList.add(this.options.classPrefix + this.state.gridNumber); this.overlay.style.display = "none"; this.overlay.style.pointerEvents = "none"; this.overlay.style.height = document.body.scrollHeight + "px"; // Unless a custom z-index is set, ensure the overlay will be behind everything if(this.overlay.style.zIndex === "auto") { this.overlay.style.zIndex = this.overlayZBackground; } // Prepend overlay to body document.body.insertBefore(this.overlay, document.body.firstChild); // Add keyboard events listener boundKeydownHandler = keydownHandler.bind(this); boundKeyupHandler = keyupHandler.bind(this); if(document.addEventListener) { document.addEventListener("keydown", boundKeydownHandler, false); document.addEventListener("keyup", boundKeyupHandler, false); } else if(document.attachEvent){ document.attachEvent("onkeydown", boundKeydownHandler); document.attachEvent("onkeyup", boundKeyupHandler); } fillGrid.call(this); storageData = storage.read(this.options.storagePrefix + this.options.id); // TODO: Improve storage and state management if(storageData) { if(storageData.gridNumber) { this.overlay.classList.remove(this.options.classPrefix + this.state.gridNumber); this.overlay.classList.add(this.options.classPrefix + storageData.gridNumber); this.state.gridNumber = storageData.gridNumber; } if(storageData.overlayHold) { this.overlay.style.display = "block"; this.state.overlayOn = true; this.state.overlayHold = true; } if(storageData.overlayZIndex) { if(storageData.overlayZIndex === "B"){ this.overlay.style.zIndex = this.options.overlayZBG; } else if(storageData.overlayZIndex === "F"){ this.overlay.style.zIndex = this.options.overlayZFG; } this.state.overlayZIndex = storageData.overlayZIndex; } } }; Hashgrid.prototype.showOverlay = function() { this.overlay.style.display = "block"; this.state.overlayOn = true; }; Hashgrid.prototype.hideOverlay = function() { this.overlay.style.display = "none"; this.state.overlayOn = false; }; Hashgrid.prototype.destroy = function() { // Remove grid container this.overlay.remove(); // Remove storage data storage.remove(this.options.storagePrefix + this.options.id); // Remove keyboard events listener if(document.removeEventListener) { document.removeEventListener("keydown", boundKeydownHandler); document.removeEventListener("keyup", boundKeyupHandler); } else if(document.detachevent){ document.detachEvent("onkeydown", boundKeydownHandler); document.detachEvent("onkeyup", boundKeyupHandler); } }; // Private helper functions fillGrid = function() { var columnContainer = document.createElement("div"), column = document.createElement("div"), - columnCount, + columnCount = 0, columnWidth, docFragment = document.createDocumentFragment(), options = this.options, overlay = this.overlay, overlayHeight, overlayWidth, rowContainer = document.createElement("div"), row = document.createElement("div"), - rowCount, + rowCount = 0, rowHeight; // Row and column container rowContainer.classList.add(options.id + "-row-container"); columnContainer.classList.add(options.id + "-column-container"); overlay.appendChild(rowContainer); overlay.appendChild(columnContainer); // First row and column row.classList.add(options.id + "__row"); column.classList.add(options.id + "__column"); rowContainer.appendChild(row); columnContainer.appendChild(column); // Display temporarily to get row and column size overlay.style.display = "block"; overlay.top = "-9999px"; overlayHeight = overlay.scrollHeight; overlayWidth = overlay.scrollWidth; rowHeight = row.getBoundingClientRect().height; // height + border columnWidth = column.clientWidth; // Hide it again overlay.style.display = "none"; overlay.top = "0"; - if(!rowHeight || !columnWidth) { + if(!rowHeight && !columnWidth) { return false; } - // Calculate rows and columns needed - rowCount = Math.floor(overlayHeight / rowHeight) - 1; - columnCount = Math.floor(overlayWidth / columnWidth) - 2; + if(rowHeight) { + // Calculate rows needed + rowCount = Math.floor(overlayHeight / rowHeight) - 1; - // Fill them in - while(rowCount--) { - row = document.createElement("div"); - row.classList.add(options.id + "__row"); + // Fill the rows + while(rowCount--) { + row = document.createElement("div"); + row.classList.add(options.id + "__row"); - docFragment.appendChild(row); + docFragment.appendChild(row); + } + + rowContainer.appendChild(docFragment); + } + else { + rowContainer.remove(row); } - rowContainer.appendChild(docFragment); + if(columnWidth) { + // Calculate columns needed + columnCount = Math.floor(overlayWidth / columnWidth) - 2; - while(columnCount--) { - column = document.createElement("div"); - column.classList.add(options.id + "__column"); + // Fill the columns + while(columnCount--) { + column = document.createElement("div"); + column.classList.add(options.id + "__column"); - docFragment.appendChild(column); + docFragment.appendChild(column); + } + + columnContainer.appendChild(docFragment); + } + else { + columnContainer.remove(column); } - columnContainer.appendChild(docFragment); }; keydownHandler = function(event) { var k, m, options = this.options, state = this.state, source = event.target.tagName.toLowerCase(); if ((source == 'input') || (source == 'textarea') || (source == 'select')) { return true; } m = Helper.getKeyModifier(event, options.modifierKey); if(!m) { return true; } k = Helper.getKey(event); if(!k) { return true; } if(state.isKeyDown[k]) { return true; } state.isKeyDown[k] = true; switch(k) { case options.showGridKey: if(!state.overlayOn) { this.showOverlay(); state.overlayOn = true; } else if(state.overlayHold) { this.hideOverlay(); state.overlayOn = false; state.overlayHold = false; storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; case options.holdGridKey: if(state.overlayOn && !state.overlayHold) { state.overlayHold = true; storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; case options.foregroundKey: // TODO: Turn into instance method if(state.overlayOn) { if(this.overlay.style.zIndex === options.overlayZFG) { this.overlay.style.zIndex = options.overlayZBG; state.overlayZIndex = "B"; } else { this.overlay.style.zIndex = options.overlayZFG; state.overlayZIndex = "F"; } storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; case options.jumpGridsKey: // TODO: Turn into instance method if(state.overlayOn && options.numberOfGrids > 1) { // Cycle through available grids this.overlay.classList.remove(options.classPrefix + state.gridNumber); state.gridNumber += 1; if(state.gridNumber > options.numberOfGrids) { state.gridNumber = 1; } this.overlay.classList.add(options.classPrefix + state.gridNumber); this.showOverlay(); if (/webkit/.test( navigator.userAgent.toLowerCase() )) { Helper.forceRepaint(); } storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; } return true; }; keyupHandler = function(event) { var k, m = Helper.getKeyModifier(event), options = this.options, state = this.state; if (!m) { return true; } k = Helper.getKey(event); delete state.isKeyDown[k]; if (k && (k == options.showGridKey) && !state.overlayHold) { this.hideOverlay(); state.overlayOn = false; } return true; }; createStorageData = function() { var state = this.state; return { gridNumber: state.gridNumber, overlayHold: state.overlayHold, overlayZIndex: state.overlayZIndex }; }; return Hashgrid; })(); window.Hashgrid = Hashgrid; // REMOVE START // if (typeof module!="undefined" && module.exports) module.exports = Hashgrid; // REMOVE END //
dotjay/hashgrid
6baf90d484bc7508d47e5a52177acbccebca5ae7
Cleanup helper test
diff --git a/tests/helper.js b/tests/helper.js index e1a219b..51873cd 100644 --- a/tests/helper.js +++ b/tests/helper.js @@ -1,93 +1,97 @@ var tape = require("tape"); var Helper = require("../src/helper"); function setupKeyboardEvent(keyCode, keyModifier) { // So much for dispatching event, sigh var kbdEvent = new KeyboardEvent("keydown"); var initMethod = kbdEvent.initKeyboardEvent ? "initKeyboardEvent" : "initKeyEvent"; Object.defineProperty(kbdEvent, "keyCode", { get: function() { return this.keyCodeVal; } }); Object.defineProperty(kbdEvent, "which", { get: function() { return this.keyCodeVal; } }); if(keyModifier) { Object.defineProperty(kbdEvent, keyModifier + "Key", { get: function() { return this.keyModifierVal; } }); } kbdEvent[initMethod]( "keydown", true, true, window, keyModifier === "ctrl" ? true : false, keyModifier === "alt" ? true : false, keyModifier === "shift" ? true : false, keyModifier === "metaKey" ? true : false, keyCode, 0 ); kbdEvent.keyCodeVal = keyCode; kbdEvent.keyModifierVal = true; return kbdEvent; } tape("Helper module", function(assert) { var obj1 = { a: 1, b: 2 }; var obj2 = { a: 2, c: 3 }; var obj3 = { a: 2, b: 2, c: 3 }; var keyCode = "a"; var keyModifier = "alt"; var kbdEvent = setupKeyboardEvent(keyCode.charCodeAt(0), keyModifier); assert.plan(2); assert.test("Object merge", function(assert) { assert.plan(5); assert.deepEqual(Helper.mergeObjects(), {}, "Returns an empty object when called without any arguments"); assert.deepEqual(Helper.mergeObjects("string"), {}, "Returns an empty object when one of the arguments is not an object"); assert.deepEqual(Helper.mergeObjects(obj1), obj1, "Returns the only available object for merge"); assert.deepEqual(Helper.mergeObjects(obj1, obj2), obj3, "Two objects merged properly"); assert.deepEqual(Helper.mergeObjects({}, obj1, obj2), obj3, "Three objects merged properly"); }); assert.test("Keyboard event helper", function(assert) { assert.plan(2); - document.addEventListener("keydown", function(event) { + var keydownHandler = function(event) { assert.equal(Helper.getKey(event), keyCode, "Event keyCode obtained"); assert.ok(Helper.getKeyModifier(event, keyModifier), "Event keyModifier obtained"); - }); + }; + + document.addEventListener("keydown", keydownHandler); document.documentElement.dispatchEvent(kbdEvent); + + document.removeEventListener("keydown", keydownHandler); }); });
dotjay/hashgrid
03354bec2453ec53cd120351032ae5996d714569
Remove storage and event listener when hashgrid is destroyed
diff --git a/dist/javascripts/hashgrid.js b/dist/javascripts/hashgrid.js index 525a610..a2ec396 100644 --- a/dist/javascripts/hashgrid.js +++ b/dist/javascripts/hashgrid.js @@ -1,350 +1,366 @@ (function(window, document) { var Helper = function() { + "use strict"; function copyObjectProperties(target, source) { var properties = Object.getOwnPropertyNames(source); var propertyLength = properties.length; var idx; for (idx = 0; idx < propertyLength; idx++) { target[properties[idx]] = source[properties[idx]]; } } return { getKey: function(event) { var k = false, c = event.keyCode ? event.keyCode : event.which; if (c == 13) k = "enter"; else k = String.fromCharCode(c).toLowerCase(); return k; }, getKeyModifier: function(event, modifierOption) { if (modifierOption === null) return true; var m = true; switch (modifierOption) { case "ctrl": m = event.ctrlKey ? event.ctrlKey : false; break; case "alt": m = event.altKey ? event.altKey : false; break; case "shift": m = event.shiftKey ? event.shiftKey : false; break; } return m; }, mergeObjects: function(mergedObject, obj1, obj2) { if (!mergedObject && !obj1 && !obj2) { return {}; } else if (mergedObject && typeof mergedObject !== "object" || obj1 && typeof obj1 !== "object" || obj2 && typeof obj2 !== "object") { return {}; } if (obj1) { copyObjectProperties(mergedObject, obj1); } if (obj2) { copyObjectProperties(mergedObject, obj2); } return mergedObject; }, forceRepaint: function() { var ss = document.styleSheets[0]; try { ss.addRule(".xxxxxx", "position: relative"); ss.removeRule(ss.rules.length - 1); } catch (e) {} } }; }(); var CookieStorage = function() { + "use strict"; function CookieStorage() {} CookieStorage.prototype.read = function(cookieLabel) { var cookieCrumb, cookieArray = document.cookie.split(";"), i = 0, cookieCrumbCount = cookieArray.length; cookieLabel = cookieLabel + "="; for (;i < cookieCrumbCount; i++) { cookieCrumb = cookieArray[i]; while (cookieCrumb.charAt(0) === " ") { cookieCrumb = cookieCrumb.substring(1, cookieCrumb.length); } if (cookieCrumb.indexOf(cookieLabel) === 0) { return JSON.parse(cookieCrumb.substring(cookieLabel.length, cookieCrumb.length)); } } return null; }; CookieStorage.prototype.write = function(cookieLabel, cookieValue, expirationDay) { var date, cookieExpires = "", toBeWritten = ""; if (expirationDay) { date = new Date(); date.setTime(date.getTime() + expirationDay * 24 * 60 * 60 * 1e3); cookieExpires = "; expires=" + date.toGMTString(); } toBeWritten = cookieLabel + "=" + JSON.stringify(cookieValue) + cookieExpires + "; path=/"; document.cookie = toBeWritten; return toBeWritten; }; CookieStorage.prototype.remove = function(cookieLabel) { var removedCookieValue = this.read(cookieLabel); if (removedCookieValue) { this.write(cookieLabel, "", -1); return removedCookieValue; } else { return null; } }; return CookieStorage; }(); var SessionStorage = function() { + "use strict"; function SessionStorage() { this.storage = window.sessionStorage; } SessionStorage.prototype.read = function(dataLabel) { var dataValue = this.storage.getItem(dataLabel); if (dataValue) { return JSON.parse(dataValue); } else { return null; } }; SessionStorage.prototype.write = function(dataLabel, dataValue) { this.storage.setItem(dataLabel, JSON.stringify(dataValue)); return dataValue; }; SessionStorage.prototype.remove = function(dataLabel) { var removedDataValue = this.read(dataLabel); if (removedDataValue) { this.storage.removeItem(dataLabel); return removedDataValue; } else { return null; } }; return SessionStorage; }(); var Storage = function() { - if (this.hasSessionStorage()) { - return new SessionStorage(); - } else { - return new CookieStorage(); - } - }; - Storage.prototype.hasSessionStorage = function() { - try { - var storage = window.sessionStorage, someData = "some value"; - storage.setItem(someData, someData); - storage.removeItem(someData); - return true; - } catch (e) { - return false; + "use strict"; + function Storage() { + if (this.hasSessionStorage()) { + return new SessionStorage(); + } else { + return new CookieStorage(); + } } - }; + Storage.prototype.hasSessionStorage = function() { + try { + var storage = window.sessionStorage, someData = "some value"; + storage.setItem(someData, someData); + storage.removeItem(someData); + return true; + } catch (e) { + return false; + } + }; + return Storage; + }(); var Hashgrid = function() { - var storage = new Storage(); + "use strict"; + var storage = new Storage(), fillGrid, boundKeydownHandler, keydownHandler, boundKeyupHandler, keyupHandler, createStorageData; function Hashgrid(customOptions) { var defaultOptions = { id: "hashgrid", modifierKey: null, showGridKey: "g", holdGridKey: "h", foregroundKey: "f", jumpGridsKey: "j", numberOfGrids: 1, classPrefix: "hashgrid", storagePrefix: "hashgrid" }, privateOptions = { overlayZBG: "-1", overlayZFG: "9999" }; this.options = Helper.mergeObjects(defaultOptions, customOptions, privateOptions); this.state = { overlayHold: false, overlayOn: false, overlayZIndex: "B", isKeyDown: {}, gridNumber: 1 }; this.init(); } Hashgrid.prototype.init = function() { var storageData; this.overlay = document.createElement("div"); this.overlay.id = this.options.id; this.overlay.classList.add(this.options.classPrefix + this.state.gridNumber); this.overlay.style.display = "none"; this.overlay.style.pointerEvents = "none"; this.overlay.style.height = document.body.scrollHeight + "px"; if (this.overlay.style.zIndex === "auto") { this.overlay.style.zIndex = this.overlayZBackground; } document.body.insertBefore(this.overlay, document.body.firstChild); + boundKeydownHandler = keydownHandler.bind(this); + boundKeyupHandler = keyupHandler.bind(this); if (document.addEventListener) { - document.addEventListener("keydown", keydownHandler.bind(this), false); - document.addEventListener("keyup", keyupHandler.bind(this), false); + document.addEventListener("keydown", boundKeydownHandler, false); + document.addEventListener("keyup", boundKeyupHandler, false); } else if (document.attachEvent) { - document.attachEvent("onkeydown", keydownHandler.bind(this)); - document.attachEvent("onkeyup", keyupHandler.bind(this)); + document.attachEvent("onkeydown", boundKeydownHandler); + document.attachEvent("onkeyup", boundKeyupHandler); } fillGrid.call(this); storageData = storage.read(this.options.storagePrefix + this.options.id); if (storageData) { if (storageData.gridNumber) { this.overlay.classList.remove(this.options.classPrefix + this.state.gridNumber); this.overlay.classList.add(this.options.classPrefix + storageData.gridNumber); this.state.gridNumber = storageData.gridNumber; } if (storageData.overlayHold) { this.overlay.style.display = "block"; this.state.overlayOn = true; this.state.overlayHold = true; } if (storageData.overlayZIndex) { if (storageData.overlayZIndex === "B") { this.overlay.style.zIndex = this.options.overlayZBG; } else if (storageData.overlayZIndex === "F") { this.overlay.style.zIndex = this.options.overlayZFG; } this.state.overlayZIndex = storageData.overlayZIndex; } } }; Hashgrid.prototype.showOverlay = function() { this.overlay.style.display = "block"; this.state.overlayOn = true; }; Hashgrid.prototype.hideOverlay = function() { this.overlay.style.display = "none"; this.state.overlayOn = false; }; Hashgrid.prototype.destroy = function() { this.overlay.remove(); + storage.remove(this.options.storagePrefix + this.options.id); + if (document.removeeventlistener) { + document.removeeventlistener("keydown", boundKeydownHandler, false); + document.removeeventlistener("keyup", boundKeyupHandler, false); + } else if (document.detachevent) { + document.detachevent("onkeydown", boundKeydownHandler); + document.detachevent("onkeyup", boundKeyupHandler); + } }; fillGrid = function() { var columnContainer = document.createElement("div"), column = document.createElement("div"), columnCount, columnWidth, docFragment = document.createDocumentFragment(), options = this.options, overlay = this.overlay, overlayHeight, overlayWidth, rowContainer = document.createElement("div"), row = document.createElement("div"), rowCount, rowHeight; rowContainer.classList.add(options.id + "-row-container"); columnContainer.classList.add(options.id + "-column-container"); overlay.appendChild(rowContainer); overlay.appendChild(columnContainer); row.classList.add(options.id + "__row"); column.classList.add(options.id + "__column"); rowContainer.appendChild(row); columnContainer.appendChild(column); overlay.style.display = "block"; overlay.top = "-9999px"; overlayHeight = overlay.scrollHeight; overlayWidth = overlay.scrollWidth; rowHeight = row.getBoundingClientRect().height; columnWidth = column.clientWidth; overlay.style.display = "none"; overlay.top = "0"; if (!rowHeight || !columnWidth) { return false; } rowCount = Math.floor(overlayHeight / rowHeight) - 1; columnCount = Math.floor(overlayWidth / columnWidth) - 2; while (rowCount--) { row = document.createElement("div"); row.classList.add(options.id + "__row"); docFragment.appendChild(row); } rowContainer.appendChild(docFragment); while (columnCount--) { column = document.createElement("div"); column.classList.add(options.id + "__column"); docFragment.appendChild(column); } columnContainer.appendChild(docFragment); }; keydownHandler = function(event) { - var k, m, options = this.options; - state = this.state; - source = event.target.tagName.toLowerCase(); + var k, m, options = this.options, state = this.state, source = event.target.tagName.toLowerCase(); if (source == "input" || source == "textarea" || source == "select") { return true; } m = Helper.getKeyModifier(event, options.modifierKey); if (!m) { return true; } k = Helper.getKey(event); if (!k) { return true; } if (state.isKeyDown[k]) { return true; } state.isKeyDown[k] = true; switch (k) { case options.showGridKey: if (!state.overlayOn) { this.showOverlay(); state.overlayOn = true; } else if (state.overlayHold) { this.hideOverlay(); state.overlayOn = false; state.overlayHold = false; storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; case options.holdGridKey: if (state.overlayOn && !state.overlayHold) { state.overlayHold = true; storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; case options.foregroundKey: if (state.overlayOn) { if (this.overlay.style.zIndex === options.overlayZFG) { this.overlay.style.zIndex = options.overlayZBG; state.overlayZIndex = "B"; } else { this.overlay.style.zIndex = options.overlayZFG; state.overlayZIndex = "F"; } storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; case options.jumpGridsKey: if (state.overlayOn && options.numberOfGrids > 1) { this.overlay.classList.remove(options.classPrefix + state.gridNumber); state.gridNumber += 1; if (state.gridNumber > options.numberOfGrids) { state.gridNumber = 1; } this.overlay.classList.add(options.classPrefix + state.gridNumber); this.showOverlay(); if (/webkit/.test(navigator.userAgent.toLowerCase())) { Helper.forceRepaint(); } storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; } return true; }; keyupHandler = function(event) { var k, m = Helper.getKeyModifier(event), options = this.options, state = this.state; if (!m) { return true; } k = Helper.getKey(event); delete state.isKeyDown[k]; if (k && k == options.showGridKey && !state.overlayHold) { this.hideOverlay(); state.overlayOn = false; } return true; }; createStorageData = function() { var state = this.state; return { gridNumber: state.gridNumber, overlayHold: state.overlayHold, overlayZIndex: state.overlayZIndex }; }; return Hashgrid; }(); window.Hashgrid = Hashgrid; })(window, document); \ No newline at end of file diff --git a/dist/javascripts/hashgrid.min.js b/dist/javascripts/hashgrid.min.js index 02d5666..ce82148 100644 --- a/dist/javascripts/hashgrid.min.js +++ b/dist/javascripts/hashgrid.min.js @@ -1 +1 @@ -!function(a,b){var c=function(){function a(a,b){var c,d=Object.getOwnPropertyNames(b),e=d.length;for(c=0;e>c;c++)a[d[c]]=b[d[c]]}return{getKey:function(a){var b=!1,c=a.keyCode?a.keyCode:a.which;return b=13==c?"enter":String.fromCharCode(c).toLowerCase()},getKeyModifier:function(a,b){if(null===b)return!0;var c=!0;switch(b){case"ctrl":c=a.ctrlKey?a.ctrlKey:!1;break;case"alt":c=a.altKey?a.altKey:!1;break;case"shift":c=a.shiftKey?a.shiftKey:!1}return c},mergeObjects:function(b,c,d){return b||c||d?b&&"object"!=typeof b||c&&"object"!=typeof c||d&&"object"!=typeof d?{}:(c&&a(b,c),d&&a(b,d),b):{}},forceRepaint:function(){var a=b.styleSheets[0];try{a.addRule(".xxxxxx","position: relative"),a.removeRule(a.rules.length-1)}catch(c){}}}}(),d=function(){function a(){}return a.prototype.read=function(a){var c,d=b.cookie.split(";"),e=0,f=d.length;for(a+="=";f>e;e++){for(c=d[e];" "===c.charAt(0);)c=c.substring(1,c.length);if(0===c.indexOf(a))return JSON.parse(c.substring(a.length,c.length))}return null},a.prototype.write=function(a,c,d){var e,f="",g="";return d&&(e=new Date,e.setTime(e.getTime()+24*d*60*60*1e3),f="; expires="+e.toGMTString()),g=a+"="+JSON.stringify(c)+f+"; path=/",b.cookie=g,g},a.prototype.remove=function(a){var b=this.read(a);return b?(this.write(a,"",-1),b):null},a}(),e=function(){function b(){this.storage=a.sessionStorage}return b.prototype.read=function(a){var b=this.storage.getItem(a);return b?JSON.parse(b):null},b.prototype.write=function(a,b){return this.storage.setItem(a,JSON.stringify(b)),b},b.prototype.remove=function(a){var b=this.read(a);return b?(this.storage.removeItem(a),b):null},b}(),f=function(){return this.hasSessionStorage()?new e:new d};f.prototype.hasSessionStorage=function(){try{var b=a.sessionStorage,c="some value";return b.setItem(c,c),b.removeItem(c),!0}catch(d){return!1}};var g=function(){function a(a){var b={id:"hashgrid",modifierKey:null,showGridKey:"g",holdGridKey:"h",foregroundKey:"f",jumpGridsKey:"j",numberOfGrids:1,classPrefix:"hashgrid",storagePrefix:"hashgrid"},d={overlayZBG:"-1",overlayZFG:"9999"};this.options=c.mergeObjects(b,a,d),this.state={overlayHold:!1,overlayOn:!1,overlayZIndex:"B",isKeyDown:{},gridNumber:1},this.init()}var d=new f;return a.prototype.init=function(){var a;this.overlay=b.createElement("div"),this.overlay.id=this.options.id,this.overlay.classList.add(this.options.classPrefix+this.state.gridNumber),this.overlay.style.display="none",this.overlay.style.pointerEvents="none",this.overlay.style.height=b.body.scrollHeight+"px","auto"===this.overlay.style.zIndex&&(this.overlay.style.zIndex=this.overlayZBackground),b.body.insertBefore(this.overlay,b.body.firstChild),b.addEventListener?(b.addEventListener("keydown",keydownHandler.bind(this),!1),b.addEventListener("keyup",keyupHandler.bind(this),!1)):b.attachEvent&&(b.attachEvent("onkeydown",keydownHandler.bind(this)),b.attachEvent("onkeyup",keyupHandler.bind(this))),fillGrid.call(this),a=d.read(this.options.storagePrefix+this.options.id),a&&(a.gridNumber&&(this.overlay.classList.remove(this.options.classPrefix+this.state.gridNumber),this.overlay.classList.add(this.options.classPrefix+a.gridNumber),this.state.gridNumber=a.gridNumber),a.overlayHold&&(this.overlay.style.display="block",this.state.overlayOn=!0,this.state.overlayHold=!0),a.overlayZIndex&&("B"===a.overlayZIndex?this.overlay.style.zIndex=this.options.overlayZBG:"F"===a.overlayZIndex&&(this.overlay.style.zIndex=this.options.overlayZFG),this.state.overlayZIndex=a.overlayZIndex))},a.prototype.showOverlay=function(){this.overlay.style.display="block",this.state.overlayOn=!0},a.prototype.hideOverlay=function(){this.overlay.style.display="none",this.state.overlayOn=!1},a.prototype.destroy=function(){this.overlay.remove()},fillGrid=function(){var a,c,d,e,f,g,h=b.createElement("div"),i=b.createElement("div"),j=b.createDocumentFragment(),k=this.options,l=this.overlay,m=b.createElement("div"),n=b.createElement("div");if(m.classList.add(k.id+"-row-container"),h.classList.add(k.id+"-column-container"),l.appendChild(m),l.appendChild(h),n.classList.add(k.id+"__row"),i.classList.add(k.id+"__column"),m.appendChild(n),h.appendChild(i),l.style.display="block",l.top="-9999px",d=l.scrollHeight,e=l.scrollWidth,g=n.getBoundingClientRect().height,c=i.clientWidth,l.style.display="none",l.top="0",!g||!c)return!1;for(f=Math.floor(d/g)-1,a=Math.floor(e/c)-2;f--;)n=b.createElement("div"),n.classList.add(k.id+"__row"),j.appendChild(n);for(m.appendChild(j);a--;)i=b.createElement("div"),i.classList.add(k.id+"__column"),j.appendChild(i);h.appendChild(j)},keydownHandler=function(a){var b,e,f=this.options;if(state=this.state,source=a.target.tagName.toLowerCase(),"input"==source||"textarea"==source||"select"==source)return!0;if(e=c.getKeyModifier(a,f.modifierKey),!e)return!0;if(b=c.getKey(a),!b)return!0;if(state.isKeyDown[b])return!0;switch(state.isKeyDown[b]=!0,b){case f.showGridKey:state.overlayOn?state.overlayHold&&(this.hideOverlay(),state.overlayOn=!1,state.overlayHold=!1,d.write(f.storagePrefix+f.id,createStorageData.call(this))):(this.showOverlay(),state.overlayOn=!0);break;case f.holdGridKey:state.overlayOn&&!state.overlayHold&&(state.overlayHold=!0,d.write(f.storagePrefix+f.id,createStorageData.call(this)));break;case f.foregroundKey:state.overlayOn&&(this.overlay.style.zIndex===f.overlayZFG?(this.overlay.style.zIndex=f.overlayZBG,state.overlayZIndex="B"):(this.overlay.style.zIndex=f.overlayZFG,state.overlayZIndex="F"),d.write(f.storagePrefix+f.id,createStorageData.call(this)));break;case f.jumpGridsKey:state.overlayOn&&f.numberOfGrids>1&&(this.overlay.classList.remove(f.classPrefix+state.gridNumber),state.gridNumber+=1,state.gridNumber>f.numberOfGrids&&(state.gridNumber=1),this.overlay.classList.add(f.classPrefix+state.gridNumber),this.showOverlay(),/webkit/.test(navigator.userAgent.toLowerCase())&&c.forceRepaint(),d.write(f.storagePrefix+f.id,createStorageData.call(this)))}return!0},keyupHandler=function(a){var b,d=c.getKeyModifier(a),e=this.options,f=this.state;return d?(b=c.getKey(a),delete f.isKeyDown[b],b&&b==e.showGridKey&&!f.overlayHold&&(this.hideOverlay(),f.overlayOn=!1),!0):!0},createStorageData=function(){var a=this.state;return{gridNumber:a.gridNumber,overlayHold:a.overlayHold,overlayZIndex:a.overlayZIndex}},a}();a.Hashgrid=g}(window,document); \ No newline at end of file +!function(a,b){var c=function(){"use strict";function a(a,b){var c,d=Object.getOwnPropertyNames(b),e=d.length;for(c=0;e>c;c++)a[d[c]]=b[d[c]]}return{getKey:function(a){var b=!1,c=a.keyCode?a.keyCode:a.which;return b=13==c?"enter":String.fromCharCode(c).toLowerCase()},getKeyModifier:function(a,b){if(null===b)return!0;var c=!0;switch(b){case"ctrl":c=a.ctrlKey?a.ctrlKey:!1;break;case"alt":c=a.altKey?a.altKey:!1;break;case"shift":c=a.shiftKey?a.shiftKey:!1}return c},mergeObjects:function(b,c,d){return b||c||d?b&&"object"!=typeof b||c&&"object"!=typeof c||d&&"object"!=typeof d?{}:(c&&a(b,c),d&&a(b,d),b):{}},forceRepaint:function(){var a=b.styleSheets[0];try{a.addRule(".xxxxxx","position: relative"),a.removeRule(a.rules.length-1)}catch(c){}}}}(),d=function(){"use strict";function a(){}return a.prototype.read=function(a){var c,d=b.cookie.split(";"),e=0,f=d.length;for(a+="=";f>e;e++){for(c=d[e];" "===c.charAt(0);)c=c.substring(1,c.length);if(0===c.indexOf(a))return JSON.parse(c.substring(a.length,c.length))}return null},a.prototype.write=function(a,c,d){var e,f="",g="";return d&&(e=new Date,e.setTime(e.getTime()+24*d*60*60*1e3),f="; expires="+e.toGMTString()),g=a+"="+JSON.stringify(c)+f+"; path=/",b.cookie=g,g},a.prototype.remove=function(a){var b=this.read(a);return b?(this.write(a,"",-1),b):null},a}(),e=function(){"use strict";function b(){this.storage=a.sessionStorage}return b.prototype.read=function(a){var b=this.storage.getItem(a);return b?JSON.parse(b):null},b.prototype.write=function(a,b){return this.storage.setItem(a,JSON.stringify(b)),b},b.prototype.remove=function(a){var b=this.read(a);return b?(this.storage.removeItem(a),b):null},b}(),f=function(){"use strict";function b(){return this.hasSessionStorage()?new e:new d}return b.prototype.hasSessionStorage=function(){try{var b=a.sessionStorage,c="some value";return b.setItem(c,c),b.removeItem(c),!0}catch(d){return!1}},b}(),g=function(){"use strict";function a(a){var b={id:"hashgrid",modifierKey:null,showGridKey:"g",holdGridKey:"h",foregroundKey:"f",jumpGridsKey:"j",numberOfGrids:1,classPrefix:"hashgrid",storagePrefix:"hashgrid"},d={overlayZBG:"-1",overlayZFG:"9999"};this.options=c.mergeObjects(b,a,d),this.state={overlayHold:!1,overlayOn:!1,overlayZIndex:"B",isKeyDown:{},gridNumber:1},this.init()}var d,e,g,h,i,j,k=new f;return a.prototype.init=function(){var a;this.overlay=b.createElement("div"),this.overlay.id=this.options.id,this.overlay.classList.add(this.options.classPrefix+this.state.gridNumber),this.overlay.style.display="none",this.overlay.style.pointerEvents="none",this.overlay.style.height=b.body.scrollHeight+"px","auto"===this.overlay.style.zIndex&&(this.overlay.style.zIndex=this.overlayZBackground),b.body.insertBefore(this.overlay,b.body.firstChild),e=g.bind(this),h=i.bind(this),b.addEventListener?(b.addEventListener("keydown",e,!1),b.addEventListener("keyup",h,!1)):b.attachEvent&&(b.attachEvent("onkeydown",e),b.attachEvent("onkeyup",h)),d.call(this),a=k.read(this.options.storagePrefix+this.options.id),a&&(a.gridNumber&&(this.overlay.classList.remove(this.options.classPrefix+this.state.gridNumber),this.overlay.classList.add(this.options.classPrefix+a.gridNumber),this.state.gridNumber=a.gridNumber),a.overlayHold&&(this.overlay.style.display="block",this.state.overlayOn=!0,this.state.overlayHold=!0),a.overlayZIndex&&("B"===a.overlayZIndex?this.overlay.style.zIndex=this.options.overlayZBG:"F"===a.overlayZIndex&&(this.overlay.style.zIndex=this.options.overlayZFG),this.state.overlayZIndex=a.overlayZIndex))},a.prototype.showOverlay=function(){this.overlay.style.display="block",this.state.overlayOn=!0},a.prototype.hideOverlay=function(){this.overlay.style.display="none",this.state.overlayOn=!1},a.prototype.destroy=function(){this.overlay.remove(),k.remove(this.options.storagePrefix+this.options.id),b.removeeventlistener?(b.removeeventlistener("keydown",e,!1),b.removeeventlistener("keyup",h,!1)):b.detachevent&&(b.detachevent("onkeydown",e),b.detachevent("onkeyup",h))},d=function(){var a,c,d,e,f,g,h=b.createElement("div"),i=b.createElement("div"),j=b.createDocumentFragment(),k=this.options,l=this.overlay,m=b.createElement("div"),n=b.createElement("div");if(m.classList.add(k.id+"-row-container"),h.classList.add(k.id+"-column-container"),l.appendChild(m),l.appendChild(h),n.classList.add(k.id+"__row"),i.classList.add(k.id+"__column"),m.appendChild(n),h.appendChild(i),l.style.display="block",l.top="-9999px",d=l.scrollHeight,e=l.scrollWidth,g=n.getBoundingClientRect().height,c=i.clientWidth,l.style.display="none",l.top="0",!g||!c)return!1;for(f=Math.floor(d/g)-1,a=Math.floor(e/c)-2;f--;)n=b.createElement("div"),n.classList.add(k.id+"__row"),j.appendChild(n);for(m.appendChild(j);a--;)i=b.createElement("div"),i.classList.add(k.id+"__column"),j.appendChild(i);h.appendChild(j)},g=function(a){var b,d,e=this.options,f=this.state,g=a.target.tagName.toLowerCase();if("input"==g||"textarea"==g||"select"==g)return!0;if(d=c.getKeyModifier(a,e.modifierKey),!d)return!0;if(b=c.getKey(a),!b)return!0;if(f.isKeyDown[b])return!0;switch(f.isKeyDown[b]=!0,b){case e.showGridKey:f.overlayOn?f.overlayHold&&(this.hideOverlay(),f.overlayOn=!1,f.overlayHold=!1,k.write(e.storagePrefix+e.id,j.call(this))):(this.showOverlay(),f.overlayOn=!0);break;case e.holdGridKey:f.overlayOn&&!f.overlayHold&&(f.overlayHold=!0,k.write(e.storagePrefix+e.id,j.call(this)));break;case e.foregroundKey:f.overlayOn&&(this.overlay.style.zIndex===e.overlayZFG?(this.overlay.style.zIndex=e.overlayZBG,f.overlayZIndex="B"):(this.overlay.style.zIndex=e.overlayZFG,f.overlayZIndex="F"),k.write(e.storagePrefix+e.id,j.call(this)));break;case e.jumpGridsKey:f.overlayOn&&e.numberOfGrids>1&&(this.overlay.classList.remove(e.classPrefix+f.gridNumber),f.gridNumber+=1,f.gridNumber>e.numberOfGrids&&(f.gridNumber=1),this.overlay.classList.add(e.classPrefix+f.gridNumber),this.showOverlay(),/webkit/.test(navigator.userAgent.toLowerCase())&&c.forceRepaint(),k.write(e.storagePrefix+e.id,j.call(this)))}return!0},i=function(a){var b,d=c.getKeyModifier(a),e=this.options,f=this.state;return d?(b=c.getKey(a),delete f.isKeyDown[b],b&&b==e.showGridKey&&!f.overlayHold&&(this.hideOverlay(),f.overlayOn=!1),!0):!0},j=function(){var a=this.state;return{gridNumber:a.gridNumber,overlayHold:a.overlayHold,overlayZIndex:a.overlayZIndex}},a}();a.Hashgrid=g}(window,document); \ No newline at end of file diff --git a/src/hashgrid.js b/src/hashgrid.js index 0e24b9a..57d2f45 100644 --- a/src/hashgrid.js +++ b/src/hashgrid.js @@ -1,375 +1,390 @@ /** * hashgrid (vanilla version) * http://github.com/dotjay/hashgrid * Version 10, 25 Nov 2015 * Written by Jon Gibbins at Analog, http://analog.coop/ * * Contibutors: * Sean Coates, http://seancoates.com/ * Phil Dokas, http://jetless.org/ * Andrew Jaswa, http://andrewjaswa.com/ * * License: * http://www.apache.org/licenses/LICENSE-2.0.html * * // Using a basic #grid setup * var grid = new Hashgrid(); * * // Using #grid with a custom id (e.g. #mygrid) * var grid = new Hashgrid("mygrid"); * * // Using #grid with additional options * var grid = new hashgrid({ * id: "mygrid", // id for the grid container * modifierKey: "alt", // optional "ctrl", "alt" or "shift" * showGridKey: "s", // key to show the grid * holdGridKey: "enter", // key to hold the grid shown * foregroundKey: "f", // key to toggle foreground/background * jumpGridsKey: "d", // key to cycle through the grids * numberOfGrids: 2, // number of grids * classPrefix: "mygrid", // prefix for rows and columns * storagePrefix: "mygrid" // prefix for storage label * }); */ // REMOVE START // if (typeof module!="undefined" && module.exports) { var Storage = require("./storage"); var Helper = require("./helper"); } // REMOVE END // var Hashgrid = (function() { + "use strict"; - var storage = new Storage(); + var + storage = new Storage(), + fillGrid, + boundKeydownHandler, + keydownHandler, + boundKeyupHandler, + keyupHandler, + createStorageData; // Constructor + function Hashgrid(customOptions) { var defaultOptions = { id: "hashgrid", // id for the grid container modifierKey: null, // optional "ctrl", "alt" or "shift" showGridKey: "g", // key to show the grid holdGridKey: "h", // key to hold the grid shown foregroundKey: "f", // key to toggle foreground/background jumpGridsKey: "j", // key to cycle through the grids numberOfGrids: 1, // number of grids classPrefix: "hashgrid", // prefix for rows and columns storagePrefix: "hashgrid" // prefix for storage label }, privateOptions = { overlayZBG: "-1", overlayZFG: "9999" }; // Apply options this.options = Helper.mergeObjects(defaultOptions, customOptions, privateOptions); this.state = { overlayHold: false, overlayOn: false, overlayZIndex: "B", isKeyDown: {}, gridNumber: 1 }; this.init(); } // Instance methods Hashgrid.prototype.init = function() { var storageData; // Create overlay, hidden before adding to DOM this.overlay = document.createElement("div"); this.overlay.id = this.options.id; this.overlay.classList.add(this.options.classPrefix + this.state.gridNumber); this.overlay.style.display = "none"; this.overlay.style.pointerEvents = "none"; this.overlay.style.height = document.body.scrollHeight + "px"; // Unless a custom z-index is set, ensure the overlay will be behind everything if(this.overlay.style.zIndex === "auto") { this.overlay.style.zIndex = this.overlayZBackground; } // Prepend overlay to body document.body.insertBefore(this.overlay, document.body.firstChild); // Add keyboard events listener - // TODO: Find a way to add event handler that is bindable and removable + boundKeydownHandler = keydownHandler.bind(this); + boundKeyupHandler = keyupHandler.bind(this); + if(document.addEventListener) { - document.addEventListener("keydown", keydownHandler.bind(this), false); - document.addEventListener("keyup", keyupHandler.bind(this), false); + document.addEventListener("keydown", boundKeydownHandler, false); + document.addEventListener("keyup", boundKeyupHandler, false); } else if(document.attachEvent){ - document.attachEvent("onkeydown", keydownHandler.bind(this)); - document.attachEvent("onkeyup", keyupHandler.bind(this)); + document.attachEvent("onkeydown", boundKeydownHandler); + document.attachEvent("onkeyup", boundKeyupHandler); } fillGrid.call(this); storageData = storage.read(this.options.storagePrefix + this.options.id); // TODO: Improve storage and state management if(storageData) { if(storageData.gridNumber) { this.overlay.classList.remove(this.options.classPrefix + this.state.gridNumber); this.overlay.classList.add(this.options.classPrefix + storageData.gridNumber); this.state.gridNumber = storageData.gridNumber; } if(storageData.overlayHold) { this.overlay.style.display = "block"; this.state.overlayOn = true; this.state.overlayHold = true; } if(storageData.overlayZIndex) { if(storageData.overlayZIndex === "B"){ this.overlay.style.zIndex = this.options.overlayZBG; } else if(storageData.overlayZIndex === "F"){ this.overlay.style.zIndex = this.options.overlayZFG; } this.state.overlayZIndex = storageData.overlayZIndex; } } }; Hashgrid.prototype.showOverlay = function() { this.overlay.style.display = "block"; this.state.overlayOn = true; }; Hashgrid.prototype.hideOverlay = function() { this.overlay.style.display = "none"; this.state.overlayOn = false; }; Hashgrid.prototype.destroy = function() { + // Remove grid container this.overlay.remove(); - // Remove keyboard events listener (these does not work) - //if(document.removeEventListener) { - //document.removeEventListener("keydown", keydownHandler, false); - //document.removeEventListener("keyup", keyupHandler, false); - //} - //else if(document.detachEvent){ - //document.detachEvent("onkeydown", keydownHandler); - //document.detachEvent("onkeyup", keyupHandler); - //} + // Remove storage data + storage.remove(this.options.storagePrefix + this.options.id); + + // Remove keyboard events listener + if(document.removeEventListener) { + document.removeEventListener("keydown", boundKeydownHandler); + document.removeEventListener("keyup", boundKeyupHandler); + } + else if(document.detachevent){ + document.detachEvent("onkeydown", boundKeydownHandler); + document.detachEvent("onkeyup", boundKeyupHandler); + } }; - // Helper functions + // Private helper functions fillGrid = function() { var columnContainer = document.createElement("div"), column = document.createElement("div"), columnCount, columnWidth, docFragment = document.createDocumentFragment(), options = this.options, overlay = this.overlay, overlayHeight, overlayWidth, rowContainer = document.createElement("div"), row = document.createElement("div"), rowCount, rowHeight; // Row and column container rowContainer.classList.add(options.id + "-row-container"); columnContainer.classList.add(options.id + "-column-container"); overlay.appendChild(rowContainer); overlay.appendChild(columnContainer); // First row and column row.classList.add(options.id + "__row"); column.classList.add(options.id + "__column"); rowContainer.appendChild(row); columnContainer.appendChild(column); // Display temporarily to get row and column size overlay.style.display = "block"; overlay.top = "-9999px"; overlayHeight = overlay.scrollHeight; overlayWidth = overlay.scrollWidth; rowHeight = row.getBoundingClientRect().height; // height + border columnWidth = column.clientWidth; // Hide it again overlay.style.display = "none"; overlay.top = "0"; if(!rowHeight || !columnWidth) { return false; } // Calculate rows and columns needed rowCount = Math.floor(overlayHeight / rowHeight) - 1; columnCount = Math.floor(overlayWidth / columnWidth) - 2; // Fill them in while(rowCount--) { row = document.createElement("div"); row.classList.add(options.id + "__row"); docFragment.appendChild(row); } rowContainer.appendChild(docFragment); while(columnCount--) { column = document.createElement("div"); column.classList.add(options.id + "__column"); docFragment.appendChild(column); } columnContainer.appendChild(docFragment); }; keydownHandler = function(event) { var k, m, - options = this.options; - state = this.state; + options = this.options, + state = this.state, source = event.target.tagName.toLowerCase(); if ((source == 'input') || (source == 'textarea') || (source == 'select')) { return true; } m = Helper.getKeyModifier(event, options.modifierKey); if(!m) { return true; } k = Helper.getKey(event); if(!k) { return true; } if(state.isKeyDown[k]) { return true; } state.isKeyDown[k] = true; switch(k) { case options.showGridKey: if(!state.overlayOn) { this.showOverlay(); state.overlayOn = true; } else if(state.overlayHold) { this.hideOverlay(); state.overlayOn = false; state.overlayHold = false; storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; case options.holdGridKey: if(state.overlayOn && !state.overlayHold) { state.overlayHold = true; storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; case options.foregroundKey: // TODO: Turn into instance method if(state.overlayOn) { if(this.overlay.style.zIndex === options.overlayZFG) { this.overlay.style.zIndex = options.overlayZBG; state.overlayZIndex = "B"; } else { this.overlay.style.zIndex = options.overlayZFG; state.overlayZIndex = "F"; } storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; case options.jumpGridsKey: // TODO: Turn into instance method if(state.overlayOn && options.numberOfGrids > 1) { // Cycle through available grids this.overlay.classList.remove(options.classPrefix + state.gridNumber); state.gridNumber += 1; if(state.gridNumber > options.numberOfGrids) { state.gridNumber = 1; } this.overlay.classList.add(options.classPrefix + state.gridNumber); this.showOverlay(); if (/webkit/.test( navigator.userAgent.toLowerCase() )) { Helper.forceRepaint(); } storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; } return true; }; keyupHandler = function(event) { var k, m = Helper.getKeyModifier(event), options = this.options, state = this.state; if (!m) { return true; } k = Helper.getKey(event); delete state.isKeyDown[k]; if (k && (k == options.showGridKey) && !state.overlayHold) { this.hideOverlay(); state.overlayOn = false; } return true; }; createStorageData = function() { var state = this.state; return { gridNumber: state.gridNumber, overlayHold: state.overlayHold, overlayZIndex: state.overlayZIndex }; }; return Hashgrid; })(); window.Hashgrid = Hashgrid; // REMOVE START // if (typeof module!="undefined" && module.exports) module.exports = Hashgrid; // REMOVE END //
dotjay/hashgrid
f9b254b6eedfd8d353594f2825ef82f30cc6264f
Use strict
diff --git a/src/cookieStorage.js b/src/cookieStorage.js index db6aeb8..56cc5e7 100644 --- a/src/cookieStorage.js +++ b/src/cookieStorage.js @@ -1,76 +1,77 @@ /** * Based on cookie functions * By Peter-Paul Koch: * http://www.quirksmode.org/js/cookies.html */ var CookieStorage = (function() { + "use strict"; function CookieStorage() { } CookieStorage.prototype.read = function(cookieLabel) { var cookieCrumb, cookieArray = document.cookie.split(";"), i = 0, cookieCrumbCount = cookieArray.length; cookieLabel = cookieLabel + "="; for(; i < cookieCrumbCount; i++) { cookieCrumb = cookieArray[i]; while(cookieCrumb.charAt(0) === " ") { cookieCrumb = cookieCrumb.substring(1, cookieCrumb.length); } if(cookieCrumb.indexOf(cookieLabel) === 0) { return JSON.parse(cookieCrumb.substring(cookieLabel.length, cookieCrumb.length)); } } return null; }; CookieStorage.prototype.write = function(cookieLabel, cookieValue, expirationDay) { var date, cookieExpires = "", toBeWritten = ""; if (expirationDay) { date = new Date(); date.setTime( date.getTime() + (expirationDay*24*60*60*1000) ); cookieExpires = "; expires=" + date.toGMTString(); } toBeWritten = cookieLabel + "=" + JSON.stringify(cookieValue) + cookieExpires + "; path=/"; document.cookie = toBeWritten; return toBeWritten; }; CookieStorage.prototype.remove = function(cookieLabel) { var removedCookieValue = this.read(cookieLabel); if(removedCookieValue) { this.write(cookieLabel, "", -1); return removedCookieValue; } else { return null; } }; return CookieStorage; })(); // REMOVE START // if (typeof module!="undefined" && module.exports) module.exports = CookieStorage; // REMOVE END // diff --git a/src/helper.js b/src/helper.js index a2e5f95..2f0b95a 100644 --- a/src/helper.js +++ b/src/helper.js @@ -1,96 +1,97 @@ var Helper = (function() { + "use strict"; function copyObjectProperties(target, source) { var properties = Object.getOwnPropertyNames(source); var propertyLength = properties.length; var idx; for(idx = 0; idx < propertyLength; idx++) { target[properties[idx]] = source[properties[idx]]; } } return { /* Keyboard event helpers */ getKey: function(event) { var k = false, c = (event.keyCode ? event.keyCode : event.which); // Handle keywords if (c == 13) k = 'enter'; // Handle letters else k = String.fromCharCode(c).toLowerCase(); return k; }, getKeyModifier: function(event, modifierOption) { if (modifierOption === null) return true; // Bypass by default var m = true; switch(modifierOption) { case 'ctrl': m = (event.ctrlKey ? event.ctrlKey : false); break; case 'alt': m = (event.altKey ? event.altKey : false); break; case 'shift': m = (event.shiftKey ? event.shiftKey : false); break; } return m; }, /* * Simple object merge * - merge obj1 and obj2 to mergedResult * - mergedResult, obj1 and obj2 can only contain primitives * - obj2 is optional */ mergeObjects: function(mergedObject, obj1, obj2) { if(!mergedObject && !obj1 && !obj2) { return {}; } else if( (mergedObject && typeof(mergedObject) !== "object") || (obj1 && typeof(obj1) !== "object") || (obj2 && typeof(obj2) !== "object")) { return {}; } if(obj1) { copyObjectProperties(mergedObject, obj1); } if(obj2) { copyObjectProperties(mergedObject, obj2); } return mergedObject; }, /** * Forces a repaint (because WebKit has issues) * http://www.sitepoint.com/forums/showthread.php?p=4538763 * http://www.phpied.com/the-new-game-show-will-it-reflow/ */ forceRepaint: function() { var ss = document.styleSheets[0]; try { ss.addRule('.xxxxxx', 'position: relative'); ss.removeRule(ss.rules.length - 1); } catch(e) {} } }; })(); // REMOVE START // if (typeof module!="undefined" && module.exports) module.exports = Helper; // REMOVE END // diff --git a/src/sessionStorage.js b/src/sessionStorage.js index aa50cb5..5aace31 100644 --- a/src/sessionStorage.js +++ b/src/sessionStorage.js @@ -1,41 +1,42 @@ var SessionStorage = (function() { + "use strict"; function SessionStorage() { this.storage = window.sessionStorage; } SessionStorage.prototype.read = function(dataLabel) { var dataValue = this.storage.getItem(dataLabel); if(dataValue) { return JSON.parse(dataValue); } else { return null; } }; SessionStorage.prototype.write = function(dataLabel, dataValue) { this.storage.setItem(dataLabel, JSON.stringify(dataValue)); return dataValue; }; SessionStorage.prototype.remove = function(dataLabel) { var removedDataValue = this.read(dataLabel); if(removedDataValue) { this.storage.removeItem(dataLabel); return removedDataValue; } else { return null; } }; return SessionStorage; })(); // REMOVE START // if (typeof module!="undefined" && module.exports) module.exports = SessionStorage; // REMOVE END // diff --git a/src/storage.js b/src/storage.js index 0b60957..16169c4 100644 --- a/src/storage.js +++ b/src/storage.js @@ -1,39 +1,45 @@ /* * This is just a proxy for storage function * Ideally, local storage is used, * cookie storage is provided only as fallback */ // REMOVE START // if (typeof module!='undefined' && module.exports) { var SessionStorage = require("./sessionStorage"); var CookieStorage = require("./cookieStorage"); } // REMOVE END // -var Storage = function() { - if(this.hasSessionStorage()) { - return new SessionStorage(); - } - else { - return new CookieStorage(); +var Storage = (function() { + "use strict"; + + function Storage() { + if(this.hasSessionStorage()) { + return new SessionStorage(); + } + else { + return new CookieStorage(); + } } -}; -Storage.prototype.hasSessionStorage = function() { - try { - var storage = window.sessionStorage, + Storage.prototype.hasSessionStorage = function() { + try { + var storage = window.sessionStorage, someData = "some value"; - storage.setItem(someData, someData); - storage.removeItem(someData); - return true; - } - catch(e) { - return false; - } -}; + storage.setItem(someData, someData); + storage.removeItem(someData); + return true; + } + catch(e) { + return false; + } + }; + + return Storage; +})(); // REMOVE START // if (typeof module!="undefined" && module.exports) module.exports = Storage; // REMOVE END //
dotjay/hashgrid
7cd2739cfbc86375438e1b14450fe7af10095377
Fix hashgrid default z-index state
diff --git a/dist/javascripts/hashgrid.js b/dist/javascripts/hashgrid.js index c0069fc..525a610 100644 --- a/dist/javascripts/hashgrid.js +++ b/dist/javascripts/hashgrid.js @@ -1,348 +1,350 @@ (function(window, document) { var Helper = function() { function copyObjectProperties(target, source) { var properties = Object.getOwnPropertyNames(source); var propertyLength = properties.length; var idx; for (idx = 0; idx < propertyLength; idx++) { target[properties[idx]] = source[properties[idx]]; } } return { getKey: function(event) { var k = false, c = event.keyCode ? event.keyCode : event.which; if (c == 13) k = "enter"; else k = String.fromCharCode(c).toLowerCase(); return k; }, getKeyModifier: function(event, modifierOption) { if (modifierOption === null) return true; var m = true; switch (modifierOption) { case "ctrl": m = event.ctrlKey ? event.ctrlKey : false; break; case "alt": m = event.altKey ? event.altKey : false; break; case "shift": m = event.shiftKey ? event.shiftKey : false; break; } return m; }, mergeObjects: function(mergedObject, obj1, obj2) { if (!mergedObject && !obj1 && !obj2) { return {}; } else if (mergedObject && typeof mergedObject !== "object" || obj1 && typeof obj1 !== "object" || obj2 && typeof obj2 !== "object") { return {}; } if (obj1) { copyObjectProperties(mergedObject, obj1); } if (obj2) { copyObjectProperties(mergedObject, obj2); } return mergedObject; }, forceRepaint: function() { var ss = document.styleSheets[0]; try { ss.addRule(".xxxxxx", "position: relative"); ss.removeRule(ss.rules.length - 1); } catch (e) {} } }; }(); var CookieStorage = function() { function CookieStorage() {} CookieStorage.prototype.read = function(cookieLabel) { var cookieCrumb, cookieArray = document.cookie.split(";"), i = 0, cookieCrumbCount = cookieArray.length; cookieLabel = cookieLabel + "="; for (;i < cookieCrumbCount; i++) { cookieCrumb = cookieArray[i]; while (cookieCrumb.charAt(0) === " ") { cookieCrumb = cookieCrumb.substring(1, cookieCrumb.length); } if (cookieCrumb.indexOf(cookieLabel) === 0) { return JSON.parse(cookieCrumb.substring(cookieLabel.length, cookieCrumb.length)); } } return null; }; CookieStorage.prototype.write = function(cookieLabel, cookieValue, expirationDay) { var date, cookieExpires = "", toBeWritten = ""; if (expirationDay) { date = new Date(); date.setTime(date.getTime() + expirationDay * 24 * 60 * 60 * 1e3); cookieExpires = "; expires=" + date.toGMTString(); } toBeWritten = cookieLabel + "=" + JSON.stringify(cookieValue) + cookieExpires + "; path=/"; document.cookie = toBeWritten; return toBeWritten; }; CookieStorage.prototype.remove = function(cookieLabel) { var removedCookieValue = this.read(cookieLabel); if (removedCookieValue) { this.write(cookieLabel, "", -1); return removedCookieValue; } else { return null; } }; return CookieStorage; }(); var SessionStorage = function() { function SessionStorage() { this.storage = window.sessionStorage; } SessionStorage.prototype.read = function(dataLabel) { var dataValue = this.storage.getItem(dataLabel); if (dataValue) { return JSON.parse(dataValue); } else { return null; } }; SessionStorage.prototype.write = function(dataLabel, dataValue) { this.storage.setItem(dataLabel, JSON.stringify(dataValue)); return dataValue; }; SessionStorage.prototype.remove = function(dataLabel) { var removedDataValue = this.read(dataLabel); if (removedDataValue) { this.storage.removeItem(dataLabel); return removedDataValue; } else { return null; } }; return SessionStorage; }(); var Storage = function() { if (this.hasSessionStorage()) { return new SessionStorage(); } else { return new CookieStorage(); } }; Storage.prototype.hasSessionStorage = function() { try { var storage = window.sessionStorage, someData = "some value"; storage.setItem(someData, someData); storage.removeItem(someData); return true; } catch (e) { return false; } }; var Hashgrid = function() { var storage = new Storage(); function Hashgrid(customOptions) { var defaultOptions = { id: "hashgrid", modifierKey: null, showGridKey: "g", holdGridKey: "h", foregroundKey: "f", jumpGridsKey: "j", numberOfGrids: 1, classPrefix: "hashgrid", storagePrefix: "hashgrid" }, privateOptions = { overlayZBG: "-1", overlayZFG: "9999" }; this.options = Helper.mergeObjects(defaultOptions, customOptions, privateOptions); - this.state = {}; - this.state.overlayHold = false; - this.state.overlayOn = false; - this.state.overlayZIndex = "B"; - this.state.isKeyDown = {}; - this.state.gridNumber = 1; + this.state = { + overlayHold: false, + overlayOn: false, + overlayZIndex: "B", + isKeyDown: {}, + gridNumber: 1 + }; this.init(); } Hashgrid.prototype.init = function() { var storageData; this.overlay = document.createElement("div"); this.overlay.id = this.options.id; this.overlay.classList.add(this.options.classPrefix + this.state.gridNumber); this.overlay.style.display = "none"; this.overlay.style.pointerEvents = "none"; this.overlay.style.height = document.body.scrollHeight + "px"; if (this.overlay.style.zIndex === "auto") { this.overlay.style.zIndex = this.overlayZBackground; } document.body.insertBefore(this.overlay, document.body.firstChild); if (document.addEventListener) { document.addEventListener("keydown", keydownHandler.bind(this), false); document.addEventListener("keyup", keyupHandler.bind(this), false); } else if (document.attachEvent) { document.attachEvent("onkeydown", keydownHandler.bind(this)); document.attachEvent("onkeyup", keyupHandler.bind(this)); } fillGrid.call(this); storageData = storage.read(this.options.storagePrefix + this.options.id); if (storageData) { if (storageData.gridNumber) { this.overlay.classList.remove(this.options.classPrefix + this.state.gridNumber); this.overlay.classList.add(this.options.classPrefix + storageData.gridNumber); this.state.gridNumber = storageData.gridNumber; } if (storageData.overlayHold) { this.overlay.style.display = "block"; this.state.overlayOn = true; this.state.overlayHold = true; } if (storageData.overlayZIndex) { if (storageData.overlayZIndex === "B") { this.overlay.style.zIndex = this.options.overlayZBG; } else if (storageData.overlayZIndex === "F") { this.overlay.style.zIndex = this.options.overlayZFG; } + this.state.overlayZIndex = storageData.overlayZIndex; } } }; Hashgrid.prototype.showOverlay = function() { this.overlay.style.display = "block"; this.state.overlayOn = true; }; Hashgrid.prototype.hideOverlay = function() { this.overlay.style.display = "none"; this.state.overlayOn = false; }; Hashgrid.prototype.destroy = function() { this.overlay.remove(); }; fillGrid = function() { var columnContainer = document.createElement("div"), column = document.createElement("div"), columnCount, columnWidth, docFragment = document.createDocumentFragment(), options = this.options, overlay = this.overlay, overlayHeight, overlayWidth, rowContainer = document.createElement("div"), row = document.createElement("div"), rowCount, rowHeight; rowContainer.classList.add(options.id + "-row-container"); columnContainer.classList.add(options.id + "-column-container"); overlay.appendChild(rowContainer); overlay.appendChild(columnContainer); row.classList.add(options.id + "__row"); column.classList.add(options.id + "__column"); rowContainer.appendChild(row); columnContainer.appendChild(column); overlay.style.display = "block"; overlay.top = "-9999px"; overlayHeight = overlay.scrollHeight; overlayWidth = overlay.scrollWidth; rowHeight = row.getBoundingClientRect().height; columnWidth = column.clientWidth; overlay.style.display = "none"; overlay.top = "0"; if (!rowHeight || !columnWidth) { return false; } rowCount = Math.floor(overlayHeight / rowHeight) - 1; columnCount = Math.floor(overlayWidth / columnWidth) - 2; while (rowCount--) { row = document.createElement("div"); row.classList.add(options.id + "__row"); docFragment.appendChild(row); } rowContainer.appendChild(docFragment); while (columnCount--) { column = document.createElement("div"); column.classList.add(options.id + "__column"); docFragment.appendChild(column); } columnContainer.appendChild(docFragment); }; keydownHandler = function(event) { var k, m, options = this.options; state = this.state; source = event.target.tagName.toLowerCase(); if (source == "input" || source == "textarea" || source == "select") { return true; } m = Helper.getKeyModifier(event, options.modifierKey); if (!m) { return true; } k = Helper.getKey(event); if (!k) { return true; } if (state.isKeyDown[k]) { return true; } state.isKeyDown[k] = true; switch (k) { case options.showGridKey: if (!state.overlayOn) { this.showOverlay(); state.overlayOn = true; } else if (state.overlayHold) { this.hideOverlay(); state.overlayOn = false; state.overlayHold = false; storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; case options.holdGridKey: if (state.overlayOn && !state.overlayHold) { state.overlayHold = true; storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; case options.foregroundKey: if (state.overlayOn) { if (this.overlay.style.zIndex === options.overlayZFG) { this.overlay.style.zIndex = options.overlayZBG; state.overlayZIndex = "B"; } else { this.overlay.style.zIndex = options.overlayZFG; state.overlayZIndex = "F"; } storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; case options.jumpGridsKey: if (state.overlayOn && options.numberOfGrids > 1) { this.overlay.classList.remove(options.classPrefix + state.gridNumber); state.gridNumber += 1; if (state.gridNumber > options.numberOfGrids) { state.gridNumber = 1; } this.overlay.classList.add(options.classPrefix + state.gridNumber); this.showOverlay(); if (/webkit/.test(navigator.userAgent.toLowerCase())) { Helper.forceRepaint(); } storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; } return true; }; keyupHandler = function(event) { var k, m = Helper.getKeyModifier(event), options = this.options, state = this.state; if (!m) { return true; } k = Helper.getKey(event); delete state.isKeyDown[k]; if (k && k == options.showGridKey && !state.overlayHold) { this.hideOverlay(); state.overlayOn = false; } return true; }; createStorageData = function() { var state = this.state; return { gridNumber: state.gridNumber, overlayHold: state.overlayHold, overlayZIndex: state.overlayZIndex }; }; return Hashgrid; }(); window.Hashgrid = Hashgrid; })(window, document); \ No newline at end of file diff --git a/dist/javascripts/hashgrid.min.js b/dist/javascripts/hashgrid.min.js index a7dc246..02d5666 100644 --- a/dist/javascripts/hashgrid.min.js +++ b/dist/javascripts/hashgrid.min.js @@ -1 +1 @@ -!function(a,b){var c=function(){function a(a,b){var c,d=Object.getOwnPropertyNames(b),e=d.length;for(c=0;e>c;c++)a[d[c]]=b[d[c]]}return{getKey:function(a){var b=!1,c=a.keyCode?a.keyCode:a.which;return b=13==c?"enter":String.fromCharCode(c).toLowerCase()},getKeyModifier:function(a,b){if(null===b)return!0;var c=!0;switch(b){case"ctrl":c=a.ctrlKey?a.ctrlKey:!1;break;case"alt":c=a.altKey?a.altKey:!1;break;case"shift":c=a.shiftKey?a.shiftKey:!1}return c},mergeObjects:function(b,c,d){return b||c||d?b&&"object"!=typeof b||c&&"object"!=typeof c||d&&"object"!=typeof d?{}:(c&&a(b,c),d&&a(b,d),b):{}},forceRepaint:function(){var a=b.styleSheets[0];try{a.addRule(".xxxxxx","position: relative"),a.removeRule(a.rules.length-1)}catch(c){}}}}(),d=function(){function a(){}return a.prototype.read=function(a){var c,d=b.cookie.split(";"),e=0,f=d.length;for(a+="=";f>e;e++){for(c=d[e];" "===c.charAt(0);)c=c.substring(1,c.length);if(0===c.indexOf(a))return JSON.parse(c.substring(a.length,c.length))}return null},a.prototype.write=function(a,c,d){var e,f="",g="";return d&&(e=new Date,e.setTime(e.getTime()+24*d*60*60*1e3),f="; expires="+e.toGMTString()),g=a+"="+JSON.stringify(c)+f+"; path=/",b.cookie=g,g},a.prototype.remove=function(a){var b=this.read(a);return b?(this.write(a,"",-1),b):null},a}(),e=function(){function b(){this.storage=a.sessionStorage}return b.prototype.read=function(a){var b=this.storage.getItem(a);return b?JSON.parse(b):null},b.prototype.write=function(a,b){return this.storage.setItem(a,JSON.stringify(b)),b},b.prototype.remove=function(a){var b=this.read(a);return b?(this.storage.removeItem(a),b):null},b}(),f=function(){return this.hasSessionStorage()?new e:new d};f.prototype.hasSessionStorage=function(){try{var b=a.sessionStorage,c="some value";return b.setItem(c,c),b.removeItem(c),!0}catch(d){return!1}};var g=function(){function a(a){var b={id:"hashgrid",modifierKey:null,showGridKey:"g",holdGridKey:"h",foregroundKey:"f",jumpGridsKey:"j",numberOfGrids:1,classPrefix:"hashgrid",storagePrefix:"hashgrid"},d={overlayZBG:"-1",overlayZFG:"9999"};this.options=c.mergeObjects(b,a,d),this.state={},this.state.overlayHold=!1,this.state.overlayOn=!1,this.state.overlayZIndex="B",this.state.isKeyDown={},this.state.gridNumber=1,this.init()}var d=new f;return a.prototype.init=function(){var a;this.overlay=b.createElement("div"),this.overlay.id=this.options.id,this.overlay.classList.add(this.options.classPrefix+this.state.gridNumber),this.overlay.style.display="none",this.overlay.style.pointerEvents="none",this.overlay.style.height=b.body.scrollHeight+"px","auto"===this.overlay.style.zIndex&&(this.overlay.style.zIndex=this.overlayZBackground),b.body.insertBefore(this.overlay,b.body.firstChild),b.addEventListener?(b.addEventListener("keydown",keydownHandler.bind(this),!1),b.addEventListener("keyup",keyupHandler.bind(this),!1)):b.attachEvent&&(b.attachEvent("onkeydown",keydownHandler.bind(this)),b.attachEvent("onkeyup",keyupHandler.bind(this))),fillGrid.call(this),a=d.read(this.options.storagePrefix+this.options.id),a&&(a.gridNumber&&(this.overlay.classList.remove(this.options.classPrefix+this.state.gridNumber),this.overlay.classList.add(this.options.classPrefix+a.gridNumber),this.state.gridNumber=a.gridNumber),a.overlayHold&&(this.overlay.style.display="block",this.state.overlayOn=!0,this.state.overlayHold=!0),a.overlayZIndex&&("B"===a.overlayZIndex?this.overlay.style.zIndex=this.options.overlayZBG:"F"===a.overlayZIndex&&(this.overlay.style.zIndex=this.options.overlayZFG)))},a.prototype.showOverlay=function(){this.overlay.style.display="block",this.state.overlayOn=!0},a.prototype.hideOverlay=function(){this.overlay.style.display="none",this.state.overlayOn=!1},a.prototype.destroy=function(){this.overlay.remove()},fillGrid=function(){var a,c,d,e,f,g,h=b.createElement("div"),i=b.createElement("div"),j=b.createDocumentFragment(),k=this.options,l=this.overlay,m=b.createElement("div"),n=b.createElement("div");if(m.classList.add(k.id+"-row-container"),h.classList.add(k.id+"-column-container"),l.appendChild(m),l.appendChild(h),n.classList.add(k.id+"__row"),i.classList.add(k.id+"__column"),m.appendChild(n),h.appendChild(i),l.style.display="block",l.top="-9999px",d=l.scrollHeight,e=l.scrollWidth,g=n.getBoundingClientRect().height,c=i.clientWidth,l.style.display="none",l.top="0",!g||!c)return!1;for(f=Math.floor(d/g)-1,a=Math.floor(e/c)-2;f--;)n=b.createElement("div"),n.classList.add(k.id+"__row"),j.appendChild(n);for(m.appendChild(j);a--;)i=b.createElement("div"),i.classList.add(k.id+"__column"),j.appendChild(i);h.appendChild(j)},keydownHandler=function(a){var b,e,f=this.options;if(state=this.state,source=a.target.tagName.toLowerCase(),"input"==source||"textarea"==source||"select"==source)return!0;if(e=c.getKeyModifier(a,f.modifierKey),!e)return!0;if(b=c.getKey(a),!b)return!0;if(state.isKeyDown[b])return!0;switch(state.isKeyDown[b]=!0,b){case f.showGridKey:state.overlayOn?state.overlayHold&&(this.hideOverlay(),state.overlayOn=!1,state.overlayHold=!1,d.write(f.storagePrefix+f.id,createStorageData.call(this))):(this.showOverlay(),state.overlayOn=!0);break;case f.holdGridKey:state.overlayOn&&!state.overlayHold&&(state.overlayHold=!0,d.write(f.storagePrefix+f.id,createStorageData.call(this)));break;case f.foregroundKey:state.overlayOn&&(this.overlay.style.zIndex===f.overlayZFG?(this.overlay.style.zIndex=f.overlayZBG,state.overlayZIndex="B"):(this.overlay.style.zIndex=f.overlayZFG,state.overlayZIndex="F"),d.write(f.storagePrefix+f.id,createStorageData.call(this)));break;case f.jumpGridsKey:state.overlayOn&&f.numberOfGrids>1&&(this.overlay.classList.remove(f.classPrefix+state.gridNumber),state.gridNumber+=1,state.gridNumber>f.numberOfGrids&&(state.gridNumber=1),this.overlay.classList.add(f.classPrefix+state.gridNumber),this.showOverlay(),/webkit/.test(navigator.userAgent.toLowerCase())&&c.forceRepaint(),d.write(f.storagePrefix+f.id,createStorageData.call(this)))}return!0},keyupHandler=function(a){var b,d=c.getKeyModifier(a),e=this.options,f=this.state;return d?(b=c.getKey(a),delete f.isKeyDown[b],b&&b==e.showGridKey&&!f.overlayHold&&(this.hideOverlay(),f.overlayOn=!1),!0):!0},createStorageData=function(){var a=this.state;return{gridNumber:a.gridNumber,overlayHold:a.overlayHold,overlayZIndex:a.overlayZIndex}},a}();a.Hashgrid=g}(window,document); \ No newline at end of file +!function(a,b){var c=function(){function a(a,b){var c,d=Object.getOwnPropertyNames(b),e=d.length;for(c=0;e>c;c++)a[d[c]]=b[d[c]]}return{getKey:function(a){var b=!1,c=a.keyCode?a.keyCode:a.which;return b=13==c?"enter":String.fromCharCode(c).toLowerCase()},getKeyModifier:function(a,b){if(null===b)return!0;var c=!0;switch(b){case"ctrl":c=a.ctrlKey?a.ctrlKey:!1;break;case"alt":c=a.altKey?a.altKey:!1;break;case"shift":c=a.shiftKey?a.shiftKey:!1}return c},mergeObjects:function(b,c,d){return b||c||d?b&&"object"!=typeof b||c&&"object"!=typeof c||d&&"object"!=typeof d?{}:(c&&a(b,c),d&&a(b,d),b):{}},forceRepaint:function(){var a=b.styleSheets[0];try{a.addRule(".xxxxxx","position: relative"),a.removeRule(a.rules.length-1)}catch(c){}}}}(),d=function(){function a(){}return a.prototype.read=function(a){var c,d=b.cookie.split(";"),e=0,f=d.length;for(a+="=";f>e;e++){for(c=d[e];" "===c.charAt(0);)c=c.substring(1,c.length);if(0===c.indexOf(a))return JSON.parse(c.substring(a.length,c.length))}return null},a.prototype.write=function(a,c,d){var e,f="",g="";return d&&(e=new Date,e.setTime(e.getTime()+24*d*60*60*1e3),f="; expires="+e.toGMTString()),g=a+"="+JSON.stringify(c)+f+"; path=/",b.cookie=g,g},a.prototype.remove=function(a){var b=this.read(a);return b?(this.write(a,"",-1),b):null},a}(),e=function(){function b(){this.storage=a.sessionStorage}return b.prototype.read=function(a){var b=this.storage.getItem(a);return b?JSON.parse(b):null},b.prototype.write=function(a,b){return this.storage.setItem(a,JSON.stringify(b)),b},b.prototype.remove=function(a){var b=this.read(a);return b?(this.storage.removeItem(a),b):null},b}(),f=function(){return this.hasSessionStorage()?new e:new d};f.prototype.hasSessionStorage=function(){try{var b=a.sessionStorage,c="some value";return b.setItem(c,c),b.removeItem(c),!0}catch(d){return!1}};var g=function(){function a(a){var b={id:"hashgrid",modifierKey:null,showGridKey:"g",holdGridKey:"h",foregroundKey:"f",jumpGridsKey:"j",numberOfGrids:1,classPrefix:"hashgrid",storagePrefix:"hashgrid"},d={overlayZBG:"-1",overlayZFG:"9999"};this.options=c.mergeObjects(b,a,d),this.state={overlayHold:!1,overlayOn:!1,overlayZIndex:"B",isKeyDown:{},gridNumber:1},this.init()}var d=new f;return a.prototype.init=function(){var a;this.overlay=b.createElement("div"),this.overlay.id=this.options.id,this.overlay.classList.add(this.options.classPrefix+this.state.gridNumber),this.overlay.style.display="none",this.overlay.style.pointerEvents="none",this.overlay.style.height=b.body.scrollHeight+"px","auto"===this.overlay.style.zIndex&&(this.overlay.style.zIndex=this.overlayZBackground),b.body.insertBefore(this.overlay,b.body.firstChild),b.addEventListener?(b.addEventListener("keydown",keydownHandler.bind(this),!1),b.addEventListener("keyup",keyupHandler.bind(this),!1)):b.attachEvent&&(b.attachEvent("onkeydown",keydownHandler.bind(this)),b.attachEvent("onkeyup",keyupHandler.bind(this))),fillGrid.call(this),a=d.read(this.options.storagePrefix+this.options.id),a&&(a.gridNumber&&(this.overlay.classList.remove(this.options.classPrefix+this.state.gridNumber),this.overlay.classList.add(this.options.classPrefix+a.gridNumber),this.state.gridNumber=a.gridNumber),a.overlayHold&&(this.overlay.style.display="block",this.state.overlayOn=!0,this.state.overlayHold=!0),a.overlayZIndex&&("B"===a.overlayZIndex?this.overlay.style.zIndex=this.options.overlayZBG:"F"===a.overlayZIndex&&(this.overlay.style.zIndex=this.options.overlayZFG),this.state.overlayZIndex=a.overlayZIndex))},a.prototype.showOverlay=function(){this.overlay.style.display="block",this.state.overlayOn=!0},a.prototype.hideOverlay=function(){this.overlay.style.display="none",this.state.overlayOn=!1},a.prototype.destroy=function(){this.overlay.remove()},fillGrid=function(){var a,c,d,e,f,g,h=b.createElement("div"),i=b.createElement("div"),j=b.createDocumentFragment(),k=this.options,l=this.overlay,m=b.createElement("div"),n=b.createElement("div");if(m.classList.add(k.id+"-row-container"),h.classList.add(k.id+"-column-container"),l.appendChild(m),l.appendChild(h),n.classList.add(k.id+"__row"),i.classList.add(k.id+"__column"),m.appendChild(n),h.appendChild(i),l.style.display="block",l.top="-9999px",d=l.scrollHeight,e=l.scrollWidth,g=n.getBoundingClientRect().height,c=i.clientWidth,l.style.display="none",l.top="0",!g||!c)return!1;for(f=Math.floor(d/g)-1,a=Math.floor(e/c)-2;f--;)n=b.createElement("div"),n.classList.add(k.id+"__row"),j.appendChild(n);for(m.appendChild(j);a--;)i=b.createElement("div"),i.classList.add(k.id+"__column"),j.appendChild(i);h.appendChild(j)},keydownHandler=function(a){var b,e,f=this.options;if(state=this.state,source=a.target.tagName.toLowerCase(),"input"==source||"textarea"==source||"select"==source)return!0;if(e=c.getKeyModifier(a,f.modifierKey),!e)return!0;if(b=c.getKey(a),!b)return!0;if(state.isKeyDown[b])return!0;switch(state.isKeyDown[b]=!0,b){case f.showGridKey:state.overlayOn?state.overlayHold&&(this.hideOverlay(),state.overlayOn=!1,state.overlayHold=!1,d.write(f.storagePrefix+f.id,createStorageData.call(this))):(this.showOverlay(),state.overlayOn=!0);break;case f.holdGridKey:state.overlayOn&&!state.overlayHold&&(state.overlayHold=!0,d.write(f.storagePrefix+f.id,createStorageData.call(this)));break;case f.foregroundKey:state.overlayOn&&(this.overlay.style.zIndex===f.overlayZFG?(this.overlay.style.zIndex=f.overlayZBG,state.overlayZIndex="B"):(this.overlay.style.zIndex=f.overlayZFG,state.overlayZIndex="F"),d.write(f.storagePrefix+f.id,createStorageData.call(this)));break;case f.jumpGridsKey:state.overlayOn&&f.numberOfGrids>1&&(this.overlay.classList.remove(f.classPrefix+state.gridNumber),state.gridNumber+=1,state.gridNumber>f.numberOfGrids&&(state.gridNumber=1),this.overlay.classList.add(f.classPrefix+state.gridNumber),this.showOverlay(),/webkit/.test(navigator.userAgent.toLowerCase())&&c.forceRepaint(),d.write(f.storagePrefix+f.id,createStorageData.call(this)))}return!0},keyupHandler=function(a){var b,d=c.getKeyModifier(a),e=this.options,f=this.state;return d?(b=c.getKey(a),delete f.isKeyDown[b],b&&b==e.showGridKey&&!f.overlayHold&&(this.hideOverlay(),f.overlayOn=!1),!0):!0},createStorageData=function(){var a=this.state;return{gridNumber:a.gridNumber,overlayHold:a.overlayHold,overlayZIndex:a.overlayZIndex}},a}();a.Hashgrid=g}(window,document); \ No newline at end of file diff --git a/src/hashgrid.js b/src/hashgrid.js index 5ce71da..0e24b9a 100644 --- a/src/hashgrid.js +++ b/src/hashgrid.js @@ -1,374 +1,375 @@ /** * hashgrid (vanilla version) * http://github.com/dotjay/hashgrid * Version 10, 25 Nov 2015 * Written by Jon Gibbins at Analog, http://analog.coop/ * * Contibutors: * Sean Coates, http://seancoates.com/ * Phil Dokas, http://jetless.org/ * Andrew Jaswa, http://andrewjaswa.com/ * * License: * http://www.apache.org/licenses/LICENSE-2.0.html * * // Using a basic #grid setup * var grid = new Hashgrid(); * * // Using #grid with a custom id (e.g. #mygrid) * var grid = new Hashgrid("mygrid"); * * // Using #grid with additional options * var grid = new hashgrid({ * id: "mygrid", // id for the grid container * modifierKey: "alt", // optional "ctrl", "alt" or "shift" * showGridKey: "s", // key to show the grid * holdGridKey: "enter", // key to hold the grid shown * foregroundKey: "f", // key to toggle foreground/background * jumpGridsKey: "d", // key to cycle through the grids * numberOfGrids: 2, // number of grids * classPrefix: "mygrid", // prefix for rows and columns * storagePrefix: "mygrid" // prefix for storage label * }); */ // REMOVE START // if (typeof module!="undefined" && module.exports) { var Storage = require("./storage"); var Helper = require("./helper"); } // REMOVE END // var Hashgrid = (function() { var storage = new Storage(); // Constructor function Hashgrid(customOptions) { var defaultOptions = { id: "hashgrid", // id for the grid container modifierKey: null, // optional "ctrl", "alt" or "shift" showGridKey: "g", // key to show the grid holdGridKey: "h", // key to hold the grid shown foregroundKey: "f", // key to toggle foreground/background jumpGridsKey: "j", // key to cycle through the grids numberOfGrids: 1, // number of grids classPrefix: "hashgrid", // prefix for rows and columns storagePrefix: "hashgrid" // prefix for storage label }, privateOptions = { overlayZBG: "-1", overlayZFG: "9999" }; // Apply options this.options = Helper.mergeObjects(defaultOptions, customOptions, privateOptions); - this.state = {}; - - this.state.overlayHold = false; - this.state.overlayOn = false; - this.state.overlayZIndex = "B"; - this.state.isKeyDown = {}; - this.state.gridNumber = 1; + this.state = { + overlayHold: false, + overlayOn: false, + overlayZIndex: "B", + isKeyDown: {}, + gridNumber: 1 + }; this.init(); } // Instance methods Hashgrid.prototype.init = function() { var storageData; // Create overlay, hidden before adding to DOM this.overlay = document.createElement("div"); this.overlay.id = this.options.id; this.overlay.classList.add(this.options.classPrefix + this.state.gridNumber); this.overlay.style.display = "none"; this.overlay.style.pointerEvents = "none"; this.overlay.style.height = document.body.scrollHeight + "px"; // Unless a custom z-index is set, ensure the overlay will be behind everything if(this.overlay.style.zIndex === "auto") { this.overlay.style.zIndex = this.overlayZBackground; } // Prepend overlay to body document.body.insertBefore(this.overlay, document.body.firstChild); // Add keyboard events listener // TODO: Find a way to add event handler that is bindable and removable if(document.addEventListener) { document.addEventListener("keydown", keydownHandler.bind(this), false); document.addEventListener("keyup", keyupHandler.bind(this), false); } else if(document.attachEvent){ document.attachEvent("onkeydown", keydownHandler.bind(this)); document.attachEvent("onkeyup", keyupHandler.bind(this)); } fillGrid.call(this); storageData = storage.read(this.options.storagePrefix + this.options.id); // TODO: Improve storage and state management if(storageData) { if(storageData.gridNumber) { this.overlay.classList.remove(this.options.classPrefix + this.state.gridNumber); this.overlay.classList.add(this.options.classPrefix + storageData.gridNumber); this.state.gridNumber = storageData.gridNumber; } if(storageData.overlayHold) { this.overlay.style.display = "block"; this.state.overlayOn = true; this.state.overlayHold = true; } if(storageData.overlayZIndex) { if(storageData.overlayZIndex === "B"){ this.overlay.style.zIndex = this.options.overlayZBG; } else if(storageData.overlayZIndex === "F"){ this.overlay.style.zIndex = this.options.overlayZFG; } + this.state.overlayZIndex = storageData.overlayZIndex; } } }; Hashgrid.prototype.showOverlay = function() { this.overlay.style.display = "block"; this.state.overlayOn = true; }; Hashgrid.prototype.hideOverlay = function() { this.overlay.style.display = "none"; this.state.overlayOn = false; }; Hashgrid.prototype.destroy = function() { this.overlay.remove(); // Remove keyboard events listener (these does not work) //if(document.removeEventListener) { //document.removeEventListener("keydown", keydownHandler, false); //document.removeEventListener("keyup", keyupHandler, false); //} //else if(document.detachEvent){ //document.detachEvent("onkeydown", keydownHandler); //document.detachEvent("onkeyup", keyupHandler); //} }; // Helper functions fillGrid = function() { var columnContainer = document.createElement("div"), column = document.createElement("div"), columnCount, columnWidth, docFragment = document.createDocumentFragment(), options = this.options, overlay = this.overlay, overlayHeight, overlayWidth, rowContainer = document.createElement("div"), row = document.createElement("div"), rowCount, rowHeight; // Row and column container rowContainer.classList.add(options.id + "-row-container"); columnContainer.classList.add(options.id + "-column-container"); overlay.appendChild(rowContainer); overlay.appendChild(columnContainer); // First row and column row.classList.add(options.id + "__row"); column.classList.add(options.id + "__column"); rowContainer.appendChild(row); columnContainer.appendChild(column); // Display temporarily to get row and column size overlay.style.display = "block"; overlay.top = "-9999px"; overlayHeight = overlay.scrollHeight; overlayWidth = overlay.scrollWidth; rowHeight = row.getBoundingClientRect().height; // height + border columnWidth = column.clientWidth; // Hide it again overlay.style.display = "none"; overlay.top = "0"; if(!rowHeight || !columnWidth) { return false; } // Calculate rows and columns needed rowCount = Math.floor(overlayHeight / rowHeight) - 1; columnCount = Math.floor(overlayWidth / columnWidth) - 2; // Fill them in while(rowCount--) { row = document.createElement("div"); row.classList.add(options.id + "__row"); docFragment.appendChild(row); } rowContainer.appendChild(docFragment); while(columnCount--) { column = document.createElement("div"); column.classList.add(options.id + "__column"); docFragment.appendChild(column); } columnContainer.appendChild(docFragment); }; keydownHandler = function(event) { var k, m, options = this.options; state = this.state; source = event.target.tagName.toLowerCase(); if ((source == 'input') || (source == 'textarea') || (source == 'select')) { return true; } m = Helper.getKeyModifier(event, options.modifierKey); if(!m) { return true; } k = Helper.getKey(event); if(!k) { return true; } if(state.isKeyDown[k]) { return true; } state.isKeyDown[k] = true; switch(k) { case options.showGridKey: if(!state.overlayOn) { this.showOverlay(); state.overlayOn = true; } else if(state.overlayHold) { this.hideOverlay(); state.overlayOn = false; state.overlayHold = false; storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; case options.holdGridKey: if(state.overlayOn && !state.overlayHold) { state.overlayHold = true; storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; case options.foregroundKey: // TODO: Turn into instance method if(state.overlayOn) { if(this.overlay.style.zIndex === options.overlayZFG) { this.overlay.style.zIndex = options.overlayZBG; state.overlayZIndex = "B"; } else { this.overlay.style.zIndex = options.overlayZFG; state.overlayZIndex = "F"; } storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; case options.jumpGridsKey: // TODO: Turn into instance method if(state.overlayOn && options.numberOfGrids > 1) { // Cycle through available grids this.overlay.classList.remove(options.classPrefix + state.gridNumber); state.gridNumber += 1; if(state.gridNumber > options.numberOfGrids) { state.gridNumber = 1; } this.overlay.classList.add(options.classPrefix + state.gridNumber); this.showOverlay(); if (/webkit/.test( navigator.userAgent.toLowerCase() )) { Helper.forceRepaint(); } storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; } return true; }; keyupHandler = function(event) { var k, m = Helper.getKeyModifier(event), options = this.options, state = this.state; if (!m) { return true; } k = Helper.getKey(event); delete state.isKeyDown[k]; if (k && (k == options.showGridKey) && !state.overlayHold) { this.hideOverlay(); state.overlayOn = false; } return true; }; createStorageData = function() { var state = this.state; return { gridNumber: state.gridNumber, overlayHold: state.overlayHold, overlayZIndex: state.overlayZIndex }; }; return Hashgrid; })(); window.Hashgrid = Hashgrid; // REMOVE START // if (typeof module!="undefined" && module.exports) module.exports = Hashgrid; // REMOVE END //
dotjay/hashgrid
f457696bad07c4c07e7413363c7b5a3e9d94cc56
Add remove block task and update build
diff --git a/Gruntfile.js b/Gruntfile.js index ad2e51e..28bc874 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -1,14 +1,25 @@ module.exports = function(grunt) { require("load-grunt-config")(grunt, { data: { srcDir: "src", buildDir: "dist", tempDir: "temp" } }); - grunt.registerTask("build", ["clean:dist", "uglify"]); + grunt.registerMultiTask("removeBlock", function() { + var removalRegEx = new RegExp('(\/\/ ' + this.options()[0] + ' \/\/)(?:[^])*?(\/\/ ' + this.options()[1] + ' \/\/)', 'g'); + + this.data.files.forEach(function(fileObj){ + var sourceFile = grunt.file.read( fileObj.src ), + removedFile = sourceFile.replace( removalRegEx, '' ), + targetFile = grunt.file.write( fileObj.dest, removedFile ); + + });// for each loop end + }); + + grunt.registerTask("build", ["clean:dist", "removeBlock", "uglify", "clean:temp"]); grunt.registerTask("dev", ["build", "watch"]); grunt.registerTask("default", "build"); }; diff --git a/dist/javascripts/hashgrid.js b/dist/javascripts/hashgrid.js index 375fdbd..c0069fc 100644 --- a/dist/javascripts/hashgrid.js +++ b/dist/javascripts/hashgrid.js @@ -1,361 +1,348 @@ (function(window, document) { var Helper = function() { function copyObjectProperties(target, source) { var properties = Object.getOwnPropertyNames(source); var propertyLength = properties.length; var idx; for (idx = 0; idx < propertyLength; idx++) { target[properties[idx]] = source[properties[idx]]; } } return { getKey: function(event) { var k = false, c = event.keyCode ? event.keyCode : event.which; if (c == 13) k = "enter"; else k = String.fromCharCode(c).toLowerCase(); return k; }, getKeyModifier: function(event, modifierOption) { if (modifierOption === null) return true; var m = true; switch (modifierOption) { case "ctrl": m = event.ctrlKey ? event.ctrlKey : false; break; case "alt": m = event.altKey ? event.altKey : false; break; case "shift": m = event.shiftKey ? event.shiftKey : false; break; } return m; }, mergeObjects: function(mergedObject, obj1, obj2) { if (!mergedObject && !obj1 && !obj2) { return {}; } else if (mergedObject && typeof mergedObject !== "object" || obj1 && typeof obj1 !== "object" || obj2 && typeof obj2 !== "object") { return {}; } if (obj1) { copyObjectProperties(mergedObject, obj1); } if (obj2) { copyObjectProperties(mergedObject, obj2); } return mergedObject; }, forceRepaint: function() { var ss = document.styleSheets[0]; try { ss.addRule(".xxxxxx", "position: relative"); ss.removeRule(ss.rules.length - 1); } catch (e) {} } }; }(); - if (typeof module != "undefined" && module.exports) module.exports = Helper; var CookieStorage = function() { function CookieStorage() {} CookieStorage.prototype.read = function(cookieLabel) { var cookieCrumb, cookieArray = document.cookie.split(";"), i = 0, cookieCrumbCount = cookieArray.length; cookieLabel = cookieLabel + "="; for (;i < cookieCrumbCount; i++) { cookieCrumb = cookieArray[i]; while (cookieCrumb.charAt(0) === " ") { cookieCrumb = cookieCrumb.substring(1, cookieCrumb.length); } if (cookieCrumb.indexOf(cookieLabel) === 0) { return JSON.parse(cookieCrumb.substring(cookieLabel.length, cookieCrumb.length)); } } return null; }; CookieStorage.prototype.write = function(cookieLabel, cookieValue, expirationDay) { var date, cookieExpires = "", toBeWritten = ""; if (expirationDay) { date = new Date(); date.setTime(date.getTime() + expirationDay * 24 * 60 * 60 * 1e3); cookieExpires = "; expires=" + date.toGMTString(); } toBeWritten = cookieLabel + "=" + JSON.stringify(cookieValue) + cookieExpires + "; path=/"; document.cookie = toBeWritten; return toBeWritten; }; CookieStorage.prototype.remove = function(cookieLabel) { var removedCookieValue = this.read(cookieLabel); if (removedCookieValue) { this.write(cookieLabel, "", -1); return removedCookieValue; } else { return null; } }; return CookieStorage; }(); - if (typeof module != "undefined" && module.exports) module.exports = CookieStorage; var SessionStorage = function() { function SessionStorage() { this.storage = window.sessionStorage; } SessionStorage.prototype.read = function(dataLabel) { var dataValue = this.storage.getItem(dataLabel); if (dataValue) { return JSON.parse(dataValue); } else { return null; } }; SessionStorage.prototype.write = function(dataLabel, dataValue) { this.storage.setItem(dataLabel, JSON.stringify(dataValue)); return dataValue; }; SessionStorage.prototype.remove = function(dataLabel) { var removedDataValue = this.read(dataLabel); if (removedDataValue) { this.storage.removeItem(dataLabel); return removedDataValue; } else { return null; } }; return SessionStorage; }(); - if (typeof module != "undefined" && module.exports) module.exports = SessionStorage; - if (typeof module != "undefined" && module.exports) { - var SessionStorage = require("./sessionStorage"); - var CookieStorage = require("./cookieStorage"); - } var Storage = function() { if (this.hasSessionStorage()) { return new SessionStorage(); } else { return new CookieStorage(); } }; Storage.prototype.hasSessionStorage = function() { try { var storage = window.sessionStorage, someData = "some value"; storage.setItem(someData, someData); storage.removeItem(someData); return true; } catch (e) { return false; } }; - if (typeof module != "undefined" && module.exports) module.exports = Storage; - if (typeof module != "undefined" && module.exports) { - var Storage = require("./storage"); - var Helper = require("./helper"); - } var Hashgrid = function() { var storage = new Storage(); function Hashgrid(customOptions) { var defaultOptions = { id: "hashgrid", modifierKey: null, showGridKey: "g", holdGridKey: "h", foregroundKey: "f", jumpGridsKey: "j", numberOfGrids: 1, classPrefix: "hashgrid", storagePrefix: "hashgrid" }, privateOptions = { overlayZBG: "-1", overlayZFG: "9999" }; this.options = Helper.mergeObjects(defaultOptions, customOptions, privateOptions); this.state = {}; this.state.overlayHold = false; this.state.overlayOn = false; this.state.overlayZIndex = "B"; this.state.isKeyDown = {}; this.state.gridNumber = 1; this.init(); } Hashgrid.prototype.init = function() { var storageData; this.overlay = document.createElement("div"); this.overlay.id = this.options.id; this.overlay.classList.add(this.options.classPrefix + this.state.gridNumber); this.overlay.style.display = "none"; this.overlay.style.pointerEvents = "none"; this.overlay.style.height = document.body.scrollHeight + "px"; if (this.overlay.style.zIndex === "auto") { this.overlay.style.zIndex = this.overlayZBackground; } document.body.insertBefore(this.overlay, document.body.firstChild); if (document.addEventListener) { document.addEventListener("keydown", keydownHandler.bind(this), false); document.addEventListener("keyup", keyupHandler.bind(this), false); } else if (document.attachEvent) { document.attachEvent("onkeydown", keydownHandler.bind(this)); document.attachEvent("onkeyup", keyupHandler.bind(this)); } fillGrid.call(this); storageData = storage.read(this.options.storagePrefix + this.options.id); if (storageData) { if (storageData.gridNumber) { this.overlay.classList.remove(this.options.classPrefix + this.state.gridNumber); this.overlay.classList.add(this.options.classPrefix + storageData.gridNumber); this.state.gridNumber = storageData.gridNumber; } if (storageData.overlayHold) { this.overlay.style.display = "block"; this.state.overlayOn = true; this.state.overlayHold = true; } if (storageData.overlayZIndex) { if (storageData.overlayZIndex === "B") { this.overlay.style.zIndex = this.options.overlayZBG; } else if (storageData.overlayZIndex === "F") { this.overlay.style.zIndex = this.options.overlayZFG; } } } }; Hashgrid.prototype.showOverlay = function() { this.overlay.style.display = "block"; this.state.overlayOn = true; }; Hashgrid.prototype.hideOverlay = function() { this.overlay.style.display = "none"; this.state.overlayOn = false; }; Hashgrid.prototype.destroy = function() { this.overlay.remove(); }; fillGrid = function() { var columnContainer = document.createElement("div"), column = document.createElement("div"), columnCount, columnWidth, docFragment = document.createDocumentFragment(), options = this.options, overlay = this.overlay, overlayHeight, overlayWidth, rowContainer = document.createElement("div"), row = document.createElement("div"), rowCount, rowHeight; rowContainer.classList.add(options.id + "-row-container"); columnContainer.classList.add(options.id + "-column-container"); overlay.appendChild(rowContainer); overlay.appendChild(columnContainer); row.classList.add(options.id + "__row"); column.classList.add(options.id + "__column"); rowContainer.appendChild(row); columnContainer.appendChild(column); overlay.style.display = "block"; overlay.top = "-9999px"; overlayHeight = overlay.scrollHeight; overlayWidth = overlay.scrollWidth; rowHeight = row.getBoundingClientRect().height; columnWidth = column.clientWidth; overlay.style.display = "none"; overlay.top = "0"; if (!rowHeight || !columnWidth) { return false; } rowCount = Math.floor(overlayHeight / rowHeight) - 1; columnCount = Math.floor(overlayWidth / columnWidth) - 2; while (rowCount--) { row = document.createElement("div"); row.classList.add(options.id + "__row"); docFragment.appendChild(row); } rowContainer.appendChild(docFragment); while (columnCount--) { column = document.createElement("div"); column.classList.add(options.id + "__column"); docFragment.appendChild(column); } columnContainer.appendChild(docFragment); }; keydownHandler = function(event) { var k, m, options = this.options; state = this.state; source = event.target.tagName.toLowerCase(); if (source == "input" || source == "textarea" || source == "select") { return true; } m = Helper.getKeyModifier(event, options.modifierKey); if (!m) { return true; } k = Helper.getKey(event); if (!k) { return true; } if (state.isKeyDown[k]) { return true; } state.isKeyDown[k] = true; switch (k) { case options.showGridKey: if (!state.overlayOn) { this.showOverlay(); state.overlayOn = true; } else if (state.overlayHold) { this.hideOverlay(); state.overlayOn = false; state.overlayHold = false; storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; case options.holdGridKey: if (state.overlayOn && !state.overlayHold) { state.overlayHold = true; storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; case options.foregroundKey: if (state.overlayOn) { if (this.overlay.style.zIndex === options.overlayZFG) { this.overlay.style.zIndex = options.overlayZBG; state.overlayZIndex = "B"; } else { this.overlay.style.zIndex = options.overlayZFG; state.overlayZIndex = "F"; } storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; case options.jumpGridsKey: if (state.overlayOn && options.numberOfGrids > 1) { this.overlay.classList.remove(options.classPrefix + state.gridNumber); state.gridNumber += 1; if (state.gridNumber > options.numberOfGrids) { state.gridNumber = 1; } this.overlay.classList.add(options.classPrefix + state.gridNumber); this.showOverlay(); if (/webkit/.test(navigator.userAgent.toLowerCase())) { Helper.forceRepaint(); } storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; } return true; }; keyupHandler = function(event) { var k, m = Helper.getKeyModifier(event), options = this.options, state = this.state; if (!m) { return true; } k = Helper.getKey(event); delete state.isKeyDown[k]; if (k && k == options.showGridKey && !state.overlayHold) { this.hideOverlay(); state.overlayOn = false; } return true; }; createStorageData = function() { var state = this.state; return { gridNumber: state.gridNumber, overlayHold: state.overlayHold, overlayZIndex: state.overlayZIndex }; }; return Hashgrid; }(); window.Hashgrid = Hashgrid; - if (typeof module != "undefined" && module.exports) module.exports = Hashgrid; })(window, document); \ No newline at end of file diff --git a/dist/javascripts/hashgrid.min.js b/dist/javascripts/hashgrid.min.js index b84da8c..a7dc246 100644 --- a/dist/javascripts/hashgrid.min.js +++ b/dist/javascripts/hashgrid.min.js @@ -1 +1 @@ -!function(a,b){var c=function(){function a(a,b){var c,d=Object.getOwnPropertyNames(b),e=d.length;for(c=0;e>c;c++)a[d[c]]=b[d[c]]}return{getKey:function(a){var b=!1,c=a.keyCode?a.keyCode:a.which;return b=13==c?"enter":String.fromCharCode(c).toLowerCase()},getKeyModifier:function(a,b){if(null===b)return!0;var c=!0;switch(b){case"ctrl":c=a.ctrlKey?a.ctrlKey:!1;break;case"alt":c=a.altKey?a.altKey:!1;break;case"shift":c=a.shiftKey?a.shiftKey:!1}return c},mergeObjects:function(b,c,d){return b||c||d?b&&"object"!=typeof b||c&&"object"!=typeof c||d&&"object"!=typeof d?{}:(c&&a(b,c),d&&a(b,d),b):{}},forceRepaint:function(){var a=b.styleSheets[0];try{a.addRule(".xxxxxx","position: relative"),a.removeRule(a.rules.length-1)}catch(c){}}}}();"undefined"!=typeof module&&module.exports&&(module.exports=c);var d=function(){function a(){}return a.prototype.read=function(a){var c,d=b.cookie.split(";"),e=0,f=d.length;for(a+="=";f>e;e++){for(c=d[e];" "===c.charAt(0);)c=c.substring(1,c.length);if(0===c.indexOf(a))return JSON.parse(c.substring(a.length,c.length))}return null},a.prototype.write=function(a,c,d){var e,f="",g="";return d&&(e=new Date,e.setTime(e.getTime()+24*d*60*60*1e3),f="; expires="+e.toGMTString()),g=a+"="+JSON.stringify(c)+f+"; path=/",b.cookie=g,g},a.prototype.remove=function(a){var b=this.read(a);return b?(this.write(a,"",-1),b):null},a}();"undefined"!=typeof module&&module.exports&&(module.exports=d);var e=function(){function b(){this.storage=a.sessionStorage}return b.prototype.read=function(a){var b=this.storage.getItem(a);return b?JSON.parse(b):null},b.prototype.write=function(a,b){return this.storage.setItem(a,JSON.stringify(b)),b},b.prototype.remove=function(a){var b=this.read(a);return b?(this.storage.removeItem(a),b):null},b}();if("undefined"!=typeof module&&module.exports&&(module.exports=e),"undefined"!=typeof module&&module.exports)var e=require("./sessionStorage"),d=require("./cookieStorage");var f=function(){return this.hasSessionStorage()?new e:new d};if(f.prototype.hasSessionStorage=function(){try{var b=a.sessionStorage,c="some value";return b.setItem(c,c),b.removeItem(c),!0}catch(d){return!1}},"undefined"!=typeof module&&module.exports&&(module.exports=f),"undefined"!=typeof module&&module.exports)var f=require("./storage"),c=require("./helper");var g=function(){function a(a){var b={id:"hashgrid",modifierKey:null,showGridKey:"g",holdGridKey:"h",foregroundKey:"f",jumpGridsKey:"j",numberOfGrids:1,classPrefix:"hashgrid",storagePrefix:"hashgrid"},d={overlayZBG:"-1",overlayZFG:"9999"};this.options=c.mergeObjects(b,a,d),this.state={},this.state.overlayHold=!1,this.state.overlayOn=!1,this.state.overlayZIndex="B",this.state.isKeyDown={},this.state.gridNumber=1,this.init()}var d=new f;return a.prototype.init=function(){var a;this.overlay=b.createElement("div"),this.overlay.id=this.options.id,this.overlay.classList.add(this.options.classPrefix+this.state.gridNumber),this.overlay.style.display="none",this.overlay.style.pointerEvents="none",this.overlay.style.height=b.body.scrollHeight+"px","auto"===this.overlay.style.zIndex&&(this.overlay.style.zIndex=this.overlayZBackground),b.body.insertBefore(this.overlay,b.body.firstChild),b.addEventListener?(b.addEventListener("keydown",keydownHandler.bind(this),!1),b.addEventListener("keyup",keyupHandler.bind(this),!1)):b.attachEvent&&(b.attachEvent("onkeydown",keydownHandler.bind(this)),b.attachEvent("onkeyup",keyupHandler.bind(this))),fillGrid.call(this),a=d.read(this.options.storagePrefix+this.options.id),a&&(a.gridNumber&&(this.overlay.classList.remove(this.options.classPrefix+this.state.gridNumber),this.overlay.classList.add(this.options.classPrefix+a.gridNumber),this.state.gridNumber=a.gridNumber),a.overlayHold&&(this.overlay.style.display="block",this.state.overlayOn=!0,this.state.overlayHold=!0),a.overlayZIndex&&("B"===a.overlayZIndex?this.overlay.style.zIndex=this.options.overlayZBG:"F"===a.overlayZIndex&&(this.overlay.style.zIndex=this.options.overlayZFG)))},a.prototype.showOverlay=function(){this.overlay.style.display="block",this.state.overlayOn=!0},a.prototype.hideOverlay=function(){this.overlay.style.display="none",this.state.overlayOn=!1},a.prototype.destroy=function(){this.overlay.remove()},fillGrid=function(){var a,c,d,e,f,g,h=b.createElement("div"),i=b.createElement("div"),j=b.createDocumentFragment(),k=this.options,l=this.overlay,m=b.createElement("div"),n=b.createElement("div");if(m.classList.add(k.id+"-row-container"),h.classList.add(k.id+"-column-container"),l.appendChild(m),l.appendChild(h),n.classList.add(k.id+"__row"),i.classList.add(k.id+"__column"),m.appendChild(n),h.appendChild(i),l.style.display="block",l.top="-9999px",d=l.scrollHeight,e=l.scrollWidth,g=n.getBoundingClientRect().height,c=i.clientWidth,l.style.display="none",l.top="0",!g||!c)return!1;for(f=Math.floor(d/g)-1,a=Math.floor(e/c)-2;f--;)n=b.createElement("div"),n.classList.add(k.id+"__row"),j.appendChild(n);for(m.appendChild(j);a--;)i=b.createElement("div"),i.classList.add(k.id+"__column"),j.appendChild(i);h.appendChild(j)},keydownHandler=function(a){var b,e,f=this.options;if(state=this.state,source=a.target.tagName.toLowerCase(),"input"==source||"textarea"==source||"select"==source)return!0;if(e=c.getKeyModifier(a,f.modifierKey),!e)return!0;if(b=c.getKey(a),!b)return!0;if(state.isKeyDown[b])return!0;switch(state.isKeyDown[b]=!0,b){case f.showGridKey:state.overlayOn?state.overlayHold&&(this.hideOverlay(),state.overlayOn=!1,state.overlayHold=!1,d.write(f.storagePrefix+f.id,createStorageData.call(this))):(this.showOverlay(),state.overlayOn=!0);break;case f.holdGridKey:state.overlayOn&&!state.overlayHold&&(state.overlayHold=!0,d.write(f.storagePrefix+f.id,createStorageData.call(this)));break;case f.foregroundKey:state.overlayOn&&(this.overlay.style.zIndex===f.overlayZFG?(this.overlay.style.zIndex=f.overlayZBG,state.overlayZIndex="B"):(this.overlay.style.zIndex=f.overlayZFG,state.overlayZIndex="F"),d.write(f.storagePrefix+f.id,createStorageData.call(this)));break;case f.jumpGridsKey:state.overlayOn&&f.numberOfGrids>1&&(this.overlay.classList.remove(f.classPrefix+state.gridNumber),state.gridNumber+=1,state.gridNumber>f.numberOfGrids&&(state.gridNumber=1),this.overlay.classList.add(f.classPrefix+state.gridNumber),this.showOverlay(),/webkit/.test(navigator.userAgent.toLowerCase())&&c.forceRepaint(),d.write(f.storagePrefix+f.id,createStorageData.call(this)))}return!0},keyupHandler=function(a){var b,d=c.getKeyModifier(a),e=this.options,f=this.state;return d?(b=c.getKey(a),delete f.isKeyDown[b],b&&b==e.showGridKey&&!f.overlayHold&&(this.hideOverlay(),f.overlayOn=!1),!0):!0},createStorageData=function(){var a=this.state;return{gridNumber:a.gridNumber,overlayHold:a.overlayHold,overlayZIndex:a.overlayZIndex}},a}();a.Hashgrid=g,"undefined"!=typeof module&&module.exports&&(module.exports=g)}(window,document); \ No newline at end of file +!function(a,b){var c=function(){function a(a,b){var c,d=Object.getOwnPropertyNames(b),e=d.length;for(c=0;e>c;c++)a[d[c]]=b[d[c]]}return{getKey:function(a){var b=!1,c=a.keyCode?a.keyCode:a.which;return b=13==c?"enter":String.fromCharCode(c).toLowerCase()},getKeyModifier:function(a,b){if(null===b)return!0;var c=!0;switch(b){case"ctrl":c=a.ctrlKey?a.ctrlKey:!1;break;case"alt":c=a.altKey?a.altKey:!1;break;case"shift":c=a.shiftKey?a.shiftKey:!1}return c},mergeObjects:function(b,c,d){return b||c||d?b&&"object"!=typeof b||c&&"object"!=typeof c||d&&"object"!=typeof d?{}:(c&&a(b,c),d&&a(b,d),b):{}},forceRepaint:function(){var a=b.styleSheets[0];try{a.addRule(".xxxxxx","position: relative"),a.removeRule(a.rules.length-1)}catch(c){}}}}(),d=function(){function a(){}return a.prototype.read=function(a){var c,d=b.cookie.split(";"),e=0,f=d.length;for(a+="=";f>e;e++){for(c=d[e];" "===c.charAt(0);)c=c.substring(1,c.length);if(0===c.indexOf(a))return JSON.parse(c.substring(a.length,c.length))}return null},a.prototype.write=function(a,c,d){var e,f="",g="";return d&&(e=new Date,e.setTime(e.getTime()+24*d*60*60*1e3),f="; expires="+e.toGMTString()),g=a+"="+JSON.stringify(c)+f+"; path=/",b.cookie=g,g},a.prototype.remove=function(a){var b=this.read(a);return b?(this.write(a,"",-1),b):null},a}(),e=function(){function b(){this.storage=a.sessionStorage}return b.prototype.read=function(a){var b=this.storage.getItem(a);return b?JSON.parse(b):null},b.prototype.write=function(a,b){return this.storage.setItem(a,JSON.stringify(b)),b},b.prototype.remove=function(a){var b=this.read(a);return b?(this.storage.removeItem(a),b):null},b}(),f=function(){return this.hasSessionStorage()?new e:new d};f.prototype.hasSessionStorage=function(){try{var b=a.sessionStorage,c="some value";return b.setItem(c,c),b.removeItem(c),!0}catch(d){return!1}};var g=function(){function a(a){var b={id:"hashgrid",modifierKey:null,showGridKey:"g",holdGridKey:"h",foregroundKey:"f",jumpGridsKey:"j",numberOfGrids:1,classPrefix:"hashgrid",storagePrefix:"hashgrid"},d={overlayZBG:"-1",overlayZFG:"9999"};this.options=c.mergeObjects(b,a,d),this.state={},this.state.overlayHold=!1,this.state.overlayOn=!1,this.state.overlayZIndex="B",this.state.isKeyDown={},this.state.gridNumber=1,this.init()}var d=new f;return a.prototype.init=function(){var a;this.overlay=b.createElement("div"),this.overlay.id=this.options.id,this.overlay.classList.add(this.options.classPrefix+this.state.gridNumber),this.overlay.style.display="none",this.overlay.style.pointerEvents="none",this.overlay.style.height=b.body.scrollHeight+"px","auto"===this.overlay.style.zIndex&&(this.overlay.style.zIndex=this.overlayZBackground),b.body.insertBefore(this.overlay,b.body.firstChild),b.addEventListener?(b.addEventListener("keydown",keydownHandler.bind(this),!1),b.addEventListener("keyup",keyupHandler.bind(this),!1)):b.attachEvent&&(b.attachEvent("onkeydown",keydownHandler.bind(this)),b.attachEvent("onkeyup",keyupHandler.bind(this))),fillGrid.call(this),a=d.read(this.options.storagePrefix+this.options.id),a&&(a.gridNumber&&(this.overlay.classList.remove(this.options.classPrefix+this.state.gridNumber),this.overlay.classList.add(this.options.classPrefix+a.gridNumber),this.state.gridNumber=a.gridNumber),a.overlayHold&&(this.overlay.style.display="block",this.state.overlayOn=!0,this.state.overlayHold=!0),a.overlayZIndex&&("B"===a.overlayZIndex?this.overlay.style.zIndex=this.options.overlayZBG:"F"===a.overlayZIndex&&(this.overlay.style.zIndex=this.options.overlayZFG)))},a.prototype.showOverlay=function(){this.overlay.style.display="block",this.state.overlayOn=!0},a.prototype.hideOverlay=function(){this.overlay.style.display="none",this.state.overlayOn=!1},a.prototype.destroy=function(){this.overlay.remove()},fillGrid=function(){var a,c,d,e,f,g,h=b.createElement("div"),i=b.createElement("div"),j=b.createDocumentFragment(),k=this.options,l=this.overlay,m=b.createElement("div"),n=b.createElement("div");if(m.classList.add(k.id+"-row-container"),h.classList.add(k.id+"-column-container"),l.appendChild(m),l.appendChild(h),n.classList.add(k.id+"__row"),i.classList.add(k.id+"__column"),m.appendChild(n),h.appendChild(i),l.style.display="block",l.top="-9999px",d=l.scrollHeight,e=l.scrollWidth,g=n.getBoundingClientRect().height,c=i.clientWidth,l.style.display="none",l.top="0",!g||!c)return!1;for(f=Math.floor(d/g)-1,a=Math.floor(e/c)-2;f--;)n=b.createElement("div"),n.classList.add(k.id+"__row"),j.appendChild(n);for(m.appendChild(j);a--;)i=b.createElement("div"),i.classList.add(k.id+"__column"),j.appendChild(i);h.appendChild(j)},keydownHandler=function(a){var b,e,f=this.options;if(state=this.state,source=a.target.tagName.toLowerCase(),"input"==source||"textarea"==source||"select"==source)return!0;if(e=c.getKeyModifier(a,f.modifierKey),!e)return!0;if(b=c.getKey(a),!b)return!0;if(state.isKeyDown[b])return!0;switch(state.isKeyDown[b]=!0,b){case f.showGridKey:state.overlayOn?state.overlayHold&&(this.hideOverlay(),state.overlayOn=!1,state.overlayHold=!1,d.write(f.storagePrefix+f.id,createStorageData.call(this))):(this.showOverlay(),state.overlayOn=!0);break;case f.holdGridKey:state.overlayOn&&!state.overlayHold&&(state.overlayHold=!0,d.write(f.storagePrefix+f.id,createStorageData.call(this)));break;case f.foregroundKey:state.overlayOn&&(this.overlay.style.zIndex===f.overlayZFG?(this.overlay.style.zIndex=f.overlayZBG,state.overlayZIndex="B"):(this.overlay.style.zIndex=f.overlayZFG,state.overlayZIndex="F"),d.write(f.storagePrefix+f.id,createStorageData.call(this)));break;case f.jumpGridsKey:state.overlayOn&&f.numberOfGrids>1&&(this.overlay.classList.remove(f.classPrefix+state.gridNumber),state.gridNumber+=1,state.gridNumber>f.numberOfGrids&&(state.gridNumber=1),this.overlay.classList.add(f.classPrefix+state.gridNumber),this.showOverlay(),/webkit/.test(navigator.userAgent.toLowerCase())&&c.forceRepaint(),d.write(f.storagePrefix+f.id,createStorageData.call(this)))}return!0},keyupHandler=function(a){var b,d=c.getKeyModifier(a),e=this.options,f=this.state;return d?(b=c.getKey(a),delete f.isKeyDown[b],b&&b==e.showGridKey&&!f.overlayHold&&(this.hideOverlay(),f.overlayOn=!1),!0):!0},createStorageData=function(){var a=this.state;return{gridNumber:a.gridNumber,overlayHold:a.overlayHold,overlayZIndex:a.overlayZIndex}},a}();a.Hashgrid=g}(window,document); \ No newline at end of file diff --git a/grunt/removeBlock.js b/grunt/removeBlock.js new file mode 100644 index 0000000..ab32a6e --- /dev/null +++ b/grunt/removeBlock.js @@ -0,0 +1,15 @@ +module.exports = { + production: { + options: [ + "REMOVE START", + "REMOVE END" + ], + files: [ + {src: "<%= srcDir %>/helper.js", dest: "<%= tempDir %>/helper.js"}, + {src: "<%= srcDir %>/cookieStorage.js", dest: "<%= tempDir %>/cookieStorage.js"}, + {src: "<%= srcDir %>/sessionStorage.js", dest: "<%= tempDir %>/sessionStorage.js"}, + {src: "<%= srcDir %>/storage.js", dest: "<%= tempDir %>/storage.js"}, + {src: "<%= srcDir %>/hashgrid.js", dest: "<%= tempDir %>/hashgrid.js"} + ] + } +}; diff --git a/grunt/uglify.js b/grunt/uglify.js index e27bdce..bddd029 100644 --- a/grunt/uglify.js +++ b/grunt/uglify.js @@ -1,39 +1,39 @@ -srcFiles = [ - "<%= srcDir %>/helper.js", - "<%= srcDir %>/cookieStorage.js", - "<%= srcDir %>/sessionStorage.js", - "<%= srcDir %>/storage.js", - "<%= srcDir %>/hashgrid.js" +var srcFiles = [ + "<%= tempDir %>/helper.js", + "<%= tempDir %>/cookieStorage.js", + "<%= tempDir %>/sessionStorage.js", + "<%= tempDir %>/storage.js", + "<%= tempDir %>/hashgrid.js" ]; module.exports = { options: { enclose: { "window": "window", "document": "document" - } + }, }, normal: { options: { mangle: false, compress: false, beautify: true }, files: { "<%= buildDir %>/javascripts/hashgrid.js": srcFiles } }, min: { options: { mangle: true, compress: true }, files: { "<%= buildDir %>/javascripts/hashgrid.min.js": srcFiles } } }; diff --git a/src/cookieStorage.js b/src/cookieStorage.js index 68cf2f4..db6aeb8 100644 --- a/src/cookieStorage.js +++ b/src/cookieStorage.js @@ -1,74 +1,76 @@ /** * Based on cookie functions * By Peter-Paul Koch: * http://www.quirksmode.org/js/cookies.html */ var CookieStorage = (function() { function CookieStorage() { } CookieStorage.prototype.read = function(cookieLabel) { var cookieCrumb, cookieArray = document.cookie.split(";"), i = 0, cookieCrumbCount = cookieArray.length; cookieLabel = cookieLabel + "="; for(; i < cookieCrumbCount; i++) { cookieCrumb = cookieArray[i]; while(cookieCrumb.charAt(0) === " ") { cookieCrumb = cookieCrumb.substring(1, cookieCrumb.length); } if(cookieCrumb.indexOf(cookieLabel) === 0) { return JSON.parse(cookieCrumb.substring(cookieLabel.length, cookieCrumb.length)); } } return null; }; CookieStorage.prototype.write = function(cookieLabel, cookieValue, expirationDay) { var date, cookieExpires = "", toBeWritten = ""; if (expirationDay) { date = new Date(); date.setTime( date.getTime() + (expirationDay*24*60*60*1000) ); cookieExpires = "; expires=" + date.toGMTString(); } toBeWritten = cookieLabel + "=" + JSON.stringify(cookieValue) + cookieExpires + "; path=/"; document.cookie = toBeWritten; return toBeWritten; }; CookieStorage.prototype.remove = function(cookieLabel) { var removedCookieValue = this.read(cookieLabel); if(removedCookieValue) { this.write(cookieLabel, "", -1); return removedCookieValue; } else { return null; } }; return CookieStorage; })(); +// REMOVE START // if (typeof module!="undefined" && module.exports) module.exports = CookieStorage; +// REMOVE END // diff --git a/src/hashgrid.js b/src/hashgrid.js index 63020e5..5ce71da 100644 --- a/src/hashgrid.js +++ b/src/hashgrid.js @@ -1,370 +1,374 @@ /** * hashgrid (vanilla version) * http://github.com/dotjay/hashgrid * Version 10, 25 Nov 2015 * Written by Jon Gibbins at Analog, http://analog.coop/ * * Contibutors: * Sean Coates, http://seancoates.com/ * Phil Dokas, http://jetless.org/ * Andrew Jaswa, http://andrewjaswa.com/ * * License: * http://www.apache.org/licenses/LICENSE-2.0.html * * // Using a basic #grid setup * var grid = new Hashgrid(); * * // Using #grid with a custom id (e.g. #mygrid) * var grid = new Hashgrid("mygrid"); * * // Using #grid with additional options * var grid = new hashgrid({ * id: "mygrid", // id for the grid container * modifierKey: "alt", // optional "ctrl", "alt" or "shift" * showGridKey: "s", // key to show the grid * holdGridKey: "enter", // key to hold the grid shown * foregroundKey: "f", // key to toggle foreground/background * jumpGridsKey: "d", // key to cycle through the grids * numberOfGrids: 2, // number of grids * classPrefix: "mygrid", // prefix for rows and columns * storagePrefix: "mygrid" // prefix for storage label * }); */ +// REMOVE START // if (typeof module!="undefined" && module.exports) { var Storage = require("./storage"); var Helper = require("./helper"); } +// REMOVE END // var Hashgrid = (function() { var storage = new Storage(); // Constructor function Hashgrid(customOptions) { var defaultOptions = { id: "hashgrid", // id for the grid container modifierKey: null, // optional "ctrl", "alt" or "shift" showGridKey: "g", // key to show the grid holdGridKey: "h", // key to hold the grid shown foregroundKey: "f", // key to toggle foreground/background jumpGridsKey: "j", // key to cycle through the grids numberOfGrids: 1, // number of grids classPrefix: "hashgrid", // prefix for rows and columns storagePrefix: "hashgrid" // prefix for storage label }, privateOptions = { overlayZBG: "-1", overlayZFG: "9999" }; // Apply options this.options = Helper.mergeObjects(defaultOptions, customOptions, privateOptions); this.state = {}; this.state.overlayHold = false; this.state.overlayOn = false; this.state.overlayZIndex = "B"; this.state.isKeyDown = {}; this.state.gridNumber = 1; this.init(); } // Instance methods Hashgrid.prototype.init = function() { var storageData; // Create overlay, hidden before adding to DOM this.overlay = document.createElement("div"); this.overlay.id = this.options.id; this.overlay.classList.add(this.options.classPrefix + this.state.gridNumber); this.overlay.style.display = "none"; this.overlay.style.pointerEvents = "none"; this.overlay.style.height = document.body.scrollHeight + "px"; // Unless a custom z-index is set, ensure the overlay will be behind everything if(this.overlay.style.zIndex === "auto") { this.overlay.style.zIndex = this.overlayZBackground; } // Prepend overlay to body document.body.insertBefore(this.overlay, document.body.firstChild); // Add keyboard events listener // TODO: Find a way to add event handler that is bindable and removable if(document.addEventListener) { document.addEventListener("keydown", keydownHandler.bind(this), false); document.addEventListener("keyup", keyupHandler.bind(this), false); } else if(document.attachEvent){ document.attachEvent("onkeydown", keydownHandler.bind(this)); document.attachEvent("onkeyup", keyupHandler.bind(this)); } fillGrid.call(this); storageData = storage.read(this.options.storagePrefix + this.options.id); // TODO: Improve storage and state management if(storageData) { if(storageData.gridNumber) { this.overlay.classList.remove(this.options.classPrefix + this.state.gridNumber); this.overlay.classList.add(this.options.classPrefix + storageData.gridNumber); this.state.gridNumber = storageData.gridNumber; } if(storageData.overlayHold) { this.overlay.style.display = "block"; this.state.overlayOn = true; this.state.overlayHold = true; } if(storageData.overlayZIndex) { if(storageData.overlayZIndex === "B"){ this.overlay.style.zIndex = this.options.overlayZBG; } else if(storageData.overlayZIndex === "F"){ this.overlay.style.zIndex = this.options.overlayZFG; } } } }; Hashgrid.prototype.showOverlay = function() { this.overlay.style.display = "block"; this.state.overlayOn = true; }; Hashgrid.prototype.hideOverlay = function() { this.overlay.style.display = "none"; this.state.overlayOn = false; }; Hashgrid.prototype.destroy = function() { this.overlay.remove(); // Remove keyboard events listener (these does not work) //if(document.removeEventListener) { //document.removeEventListener("keydown", keydownHandler, false); //document.removeEventListener("keyup", keyupHandler, false); //} //else if(document.detachEvent){ //document.detachEvent("onkeydown", keydownHandler); //document.detachEvent("onkeyup", keyupHandler); //} }; // Helper functions fillGrid = function() { var columnContainer = document.createElement("div"), column = document.createElement("div"), columnCount, columnWidth, docFragment = document.createDocumentFragment(), options = this.options, overlay = this.overlay, overlayHeight, overlayWidth, rowContainer = document.createElement("div"), row = document.createElement("div"), rowCount, rowHeight; // Row and column container rowContainer.classList.add(options.id + "-row-container"); columnContainer.classList.add(options.id + "-column-container"); overlay.appendChild(rowContainer); overlay.appendChild(columnContainer); // First row and column row.classList.add(options.id + "__row"); column.classList.add(options.id + "__column"); rowContainer.appendChild(row); columnContainer.appendChild(column); // Display temporarily to get row and column size overlay.style.display = "block"; overlay.top = "-9999px"; overlayHeight = overlay.scrollHeight; overlayWidth = overlay.scrollWidth; rowHeight = row.getBoundingClientRect().height; // height + border columnWidth = column.clientWidth; // Hide it again overlay.style.display = "none"; overlay.top = "0"; if(!rowHeight || !columnWidth) { return false; } // Calculate rows and columns needed rowCount = Math.floor(overlayHeight / rowHeight) - 1; columnCount = Math.floor(overlayWidth / columnWidth) - 2; // Fill them in while(rowCount--) { row = document.createElement("div"); row.classList.add(options.id + "__row"); docFragment.appendChild(row); } rowContainer.appendChild(docFragment); while(columnCount--) { column = document.createElement("div"); column.classList.add(options.id + "__column"); docFragment.appendChild(column); } columnContainer.appendChild(docFragment); }; keydownHandler = function(event) { var k, m, options = this.options; state = this.state; source = event.target.tagName.toLowerCase(); if ((source == 'input') || (source == 'textarea') || (source == 'select')) { return true; } m = Helper.getKeyModifier(event, options.modifierKey); if(!m) { return true; } k = Helper.getKey(event); if(!k) { return true; } if(state.isKeyDown[k]) { return true; } state.isKeyDown[k] = true; switch(k) { case options.showGridKey: if(!state.overlayOn) { this.showOverlay(); state.overlayOn = true; } else if(state.overlayHold) { this.hideOverlay(); state.overlayOn = false; state.overlayHold = false; storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; case options.holdGridKey: if(state.overlayOn && !state.overlayHold) { state.overlayHold = true; storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; case options.foregroundKey: // TODO: Turn into instance method if(state.overlayOn) { if(this.overlay.style.zIndex === options.overlayZFG) { this.overlay.style.zIndex = options.overlayZBG; state.overlayZIndex = "B"; } else { this.overlay.style.zIndex = options.overlayZFG; state.overlayZIndex = "F"; } storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; case options.jumpGridsKey: // TODO: Turn into instance method if(state.overlayOn && options.numberOfGrids > 1) { // Cycle through available grids this.overlay.classList.remove(options.classPrefix + state.gridNumber); state.gridNumber += 1; if(state.gridNumber > options.numberOfGrids) { state.gridNumber = 1; } this.overlay.classList.add(options.classPrefix + state.gridNumber); this.showOverlay(); if (/webkit/.test( navigator.userAgent.toLowerCase() )) { Helper.forceRepaint(); } storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; } return true; }; keyupHandler = function(event) { var k, m = Helper.getKeyModifier(event), options = this.options, state = this.state; if (!m) { return true; } k = Helper.getKey(event); delete state.isKeyDown[k]; if (k && (k == options.showGridKey) && !state.overlayHold) { this.hideOverlay(); state.overlayOn = false; } return true; }; createStorageData = function() { var state = this.state; return { gridNumber: state.gridNumber, overlayHold: state.overlayHold, overlayZIndex: state.overlayZIndex }; }; return Hashgrid; })(); window.Hashgrid = Hashgrid; +// REMOVE START // if (typeof module!="undefined" && module.exports) module.exports = Hashgrid; +// REMOVE END // diff --git a/src/helper.js b/src/helper.js index 83f560d..a2e5f95 100644 --- a/src/helper.js +++ b/src/helper.js @@ -1,94 +1,96 @@ var Helper = (function() { function copyObjectProperties(target, source) { var properties = Object.getOwnPropertyNames(source); var propertyLength = properties.length; var idx; for(idx = 0; idx < propertyLength; idx++) { target[properties[idx]] = source[properties[idx]]; } } return { /* Keyboard event helpers */ getKey: function(event) { var k = false, c = (event.keyCode ? event.keyCode : event.which); // Handle keywords if (c == 13) k = 'enter'; // Handle letters else k = String.fromCharCode(c).toLowerCase(); return k; }, getKeyModifier: function(event, modifierOption) { if (modifierOption === null) return true; // Bypass by default var m = true; switch(modifierOption) { case 'ctrl': m = (event.ctrlKey ? event.ctrlKey : false); break; case 'alt': m = (event.altKey ? event.altKey : false); break; case 'shift': m = (event.shiftKey ? event.shiftKey : false); break; } return m; }, /* * Simple object merge * - merge obj1 and obj2 to mergedResult * - mergedResult, obj1 and obj2 can only contain primitives * - obj2 is optional */ mergeObjects: function(mergedObject, obj1, obj2) { if(!mergedObject && !obj1 && !obj2) { return {}; } else if( (mergedObject && typeof(mergedObject) !== "object") || (obj1 && typeof(obj1) !== "object") || (obj2 && typeof(obj2) !== "object")) { return {}; } if(obj1) { copyObjectProperties(mergedObject, obj1); } if(obj2) { copyObjectProperties(mergedObject, obj2); } return mergedObject; }, /** * Forces a repaint (because WebKit has issues) * http://www.sitepoint.com/forums/showthread.php?p=4538763 * http://www.phpied.com/the-new-game-show-will-it-reflow/ */ forceRepaint: function() { var ss = document.styleSheets[0]; try { ss.addRule('.xxxxxx', 'position: relative'); ss.removeRule(ss.rules.length - 1); } catch(e) {} } }; })(); +// REMOVE START // if (typeof module!="undefined" && module.exports) module.exports = Helper; +// REMOVE END // diff --git a/src/sessionStorage.js b/src/sessionStorage.js index fafe32c..aa50cb5 100644 --- a/src/sessionStorage.js +++ b/src/sessionStorage.js @@ -1,39 +1,41 @@ var SessionStorage = (function() { function SessionStorage() { this.storage = window.sessionStorage; } SessionStorage.prototype.read = function(dataLabel) { var dataValue = this.storage.getItem(dataLabel); if(dataValue) { return JSON.parse(dataValue); } else { return null; } }; SessionStorage.prototype.write = function(dataLabel, dataValue) { this.storage.setItem(dataLabel, JSON.stringify(dataValue)); return dataValue; }; SessionStorage.prototype.remove = function(dataLabel) { var removedDataValue = this.read(dataLabel); if(removedDataValue) { this.storage.removeItem(dataLabel); return removedDataValue; } else { return null; } }; return SessionStorage; })(); +// REMOVE START // if (typeof module!="undefined" && module.exports) module.exports = SessionStorage; +// REMOVE END // diff --git a/src/storage.js b/src/storage.js index 119d89e..0b60957 100644 --- a/src/storage.js +++ b/src/storage.js @@ -1,35 +1,39 @@ /* * This is just a proxy for storage function * Ideally, local storage is used, * cookie storage is provided only as fallback */ +// REMOVE START // if (typeof module!='undefined' && module.exports) { var SessionStorage = require("./sessionStorage"); var CookieStorage = require("./cookieStorage"); } +// REMOVE END // var Storage = function() { if(this.hasSessionStorage()) { return new SessionStorage(); } else { return new CookieStorage(); } }; Storage.prototype.hasSessionStorage = function() { try { var storage = window.sessionStorage, someData = "some value"; storage.setItem(someData, someData); storage.removeItem(someData); return true; } catch(e) { return false; } }; +// REMOVE START // if (typeof module!="undefined" && module.exports) module.exports = Storage; +// REMOVE END //
dotjay/hashgrid
12fb6c070e29ca69f6e5c4fc593273da43ad9c39
Add some development instructions
diff --git a/README.md b/README.md index 119b089..1503eff 100644 --- a/README.md +++ b/README.md @@ -1,46 +1,67 @@ # #grid # A little tool that inserts a layout grid in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. ## Features ## * Adaptable for all layout widths and alignments * Adaptable for any vertical rhythm value * Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids * Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters ## Install ## Download the latest release from: https://github.com/dotjay/hashgrid/releases Install using [Bower](http://bower.io/): -``` +```bash bower install hashgrid#v10 ``` Notes on usage can be found at [hashgrid.com#installation](http://hashgrid.com/#installation). +## Development ## + +Install dependencies +```bash +npm install +``` + +Run tests +```bash +npm test +``` + +Build for production +```bash +# This will build hashgrid into dist folder +grunt + +# This will build hashgrid and then turn on the watcher for auto building +grunt dev +``` + ## License ## Copyright 2013 Analog Coop Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -- This essentially means that you're free to copy, modify and distribute it for any project so long as you provide clear attribution to Analog Coop Limited. Contact us if you need a different license. http://analog.coop/
dotjay/hashgrid
98a1bf87edd660c6f907320f212180140eb0bbdc
Implement multiple grid
diff --git a/dist/javascripts/hashgrid.js b/dist/javascripts/hashgrid.js index c972d02..375fdbd 100644 --- a/dist/javascripts/hashgrid.js +++ b/dist/javascripts/hashgrid.js @@ -1,347 +1,361 @@ (function(window, document) { var Helper = function() { function copyObjectProperties(target, source) { var properties = Object.getOwnPropertyNames(source); var propertyLength = properties.length; var idx; for (idx = 0; idx < propertyLength; idx++) { target[properties[idx]] = source[properties[idx]]; } } return { getKey: function(event) { var k = false, c = event.keyCode ? event.keyCode : event.which; if (c == 13) k = "enter"; else k = String.fromCharCode(c).toLowerCase(); return k; }, getKeyModifier: function(event, modifierOption) { if (modifierOption === null) return true; var m = true; switch (modifierOption) { case "ctrl": m = event.ctrlKey ? event.ctrlKey : false; break; case "alt": m = event.altKey ? event.altKey : false; break; case "shift": m = event.shiftKey ? event.shiftKey : false; break; } return m; }, mergeObjects: function(mergedObject, obj1, obj2) { if (!mergedObject && !obj1 && !obj2) { return {}; } else if (mergedObject && typeof mergedObject !== "object" || obj1 && typeof obj1 !== "object" || obj2 && typeof obj2 !== "object") { return {}; } if (obj1) { copyObjectProperties(mergedObject, obj1); } if (obj2) { copyObjectProperties(mergedObject, obj2); } return mergedObject; }, forceRepaint: function() { var ss = document.styleSheets[0]; try { ss.addRule(".xxxxxx", "position: relative"); ss.removeRule(ss.rules.length - 1); } catch (e) {} } }; }(); if (typeof module != "undefined" && module.exports) module.exports = Helper; var CookieStorage = function() { function CookieStorage() {} CookieStorage.prototype.read = function(cookieLabel) { var cookieCrumb, cookieArray = document.cookie.split(";"), i = 0, cookieCrumbCount = cookieArray.length; cookieLabel = cookieLabel + "="; for (;i < cookieCrumbCount; i++) { cookieCrumb = cookieArray[i]; while (cookieCrumb.charAt(0) === " ") { cookieCrumb = cookieCrumb.substring(1, cookieCrumb.length); } if (cookieCrumb.indexOf(cookieLabel) === 0) { return JSON.parse(cookieCrumb.substring(cookieLabel.length, cookieCrumb.length)); } } return null; }; CookieStorage.prototype.write = function(cookieLabel, cookieValue, expirationDay) { var date, cookieExpires = "", toBeWritten = ""; if (expirationDay) { date = new Date(); date.setTime(date.getTime() + expirationDay * 24 * 60 * 60 * 1e3); cookieExpires = "; expires=" + date.toGMTString(); } toBeWritten = cookieLabel + "=" + JSON.stringify(cookieValue) + cookieExpires + "; path=/"; document.cookie = toBeWritten; return toBeWritten; }; CookieStorage.prototype.remove = function(cookieLabel) { var removedCookieValue = this.read(cookieLabel); if (removedCookieValue) { this.write(cookieLabel, "", -1); return removedCookieValue; } else { return null; } }; return CookieStorage; }(); if (typeof module != "undefined" && module.exports) module.exports = CookieStorage; var SessionStorage = function() { function SessionStorage() { this.storage = window.sessionStorage; } SessionStorage.prototype.read = function(dataLabel) { var dataValue = this.storage.getItem(dataLabel); if (dataValue) { return JSON.parse(dataValue); } else { return null; } }; SessionStorage.prototype.write = function(dataLabel, dataValue) { this.storage.setItem(dataLabel, JSON.stringify(dataValue)); return dataValue; }; SessionStorage.prototype.remove = function(dataLabel) { var removedDataValue = this.read(dataLabel); if (removedDataValue) { this.storage.removeItem(dataLabel); return removedDataValue; } else { return null; } }; return SessionStorage; }(); if (typeof module != "undefined" && module.exports) module.exports = SessionStorage; if (typeof module != "undefined" && module.exports) { var SessionStorage = require("./sessionStorage"); var CookieStorage = require("./cookieStorage"); } var Storage = function() { if (this.hasSessionStorage()) { return new SessionStorage(); } else { return new CookieStorage(); } }; Storage.prototype.hasSessionStorage = function() { try { var storage = window.sessionStorage, someData = "some value"; storage.setItem(someData, someData); storage.removeItem(someData); return true; } catch (e) { return false; } }; if (typeof module != "undefined" && module.exports) module.exports = Storage; if (typeof module != "undefined" && module.exports) { var Storage = require("./storage"); var Helper = require("./helper"); } var Hashgrid = function() { var storage = new Storage(); function Hashgrid(customOptions) { var defaultOptions = { id: "hashgrid", modifierKey: null, showGridKey: "g", holdGridKey: "h", foregroundKey: "f", jumpGridsKey: "j", numberOfGrids: 1, classPrefix: "hashgrid", storagePrefix: "hashgrid" }, privateOptions = { overlayZBG: "-1", overlayZFG: "9999" }; this.options = Helper.mergeObjects(defaultOptions, customOptions, privateOptions); this.state = {}; this.state.overlayHold = false; this.state.overlayOn = false; this.state.overlayZIndex = "B"; this.state.isKeyDown = {}; + this.state.gridNumber = 1; this.init(); } Hashgrid.prototype.init = function() { var storageData; this.overlay = document.createElement("div"); this.overlay.id = this.options.id; + this.overlay.classList.add(this.options.classPrefix + this.state.gridNumber); this.overlay.style.display = "none"; this.overlay.style.pointerEvents = "none"; this.overlay.style.height = document.body.scrollHeight + "px"; if (this.overlay.style.zIndex === "auto") { this.overlay.style.zIndex = this.overlayZBackground; } document.body.insertBefore(this.overlay, document.body.firstChild); if (document.addEventListener) { document.addEventListener("keydown", keydownHandler.bind(this), false); document.addEventListener("keyup", keyupHandler.bind(this), false); } else if (document.attachEvent) { document.attachEvent("onkeydown", keydownHandler.bind(this)); document.attachEvent("onkeyup", keyupHandler.bind(this)); } fillGrid.call(this); storageData = storage.read(this.options.storagePrefix + this.options.id); if (storageData) { + if (storageData.gridNumber) { + this.overlay.classList.remove(this.options.classPrefix + this.state.gridNumber); + this.overlay.classList.add(this.options.classPrefix + storageData.gridNumber); + this.state.gridNumber = storageData.gridNumber; + } if (storageData.overlayHold) { this.overlay.style.display = "block"; this.state.overlayOn = true; this.state.overlayHold = true; } if (storageData.overlayZIndex) { if (storageData.overlayZIndex === "B") { this.overlay.style.zIndex = this.options.overlayZBG; } else if (storageData.overlayZIndex === "F") { this.overlay.style.zIndex = this.options.overlayZFG; } } } }; Hashgrid.prototype.showOverlay = function() { this.overlay.style.display = "block"; this.state.overlayOn = true; }; Hashgrid.prototype.hideOverlay = function() { this.overlay.style.display = "none"; this.state.overlayOn = false; }; Hashgrid.prototype.destroy = function() { this.overlay.remove(); - if (document.removeEventListener) { - document.removeEventListener("keydown", keydownHandler, false); - document.removeEventListener("keyup", keyupHandler, false); - } else if (document.detachEvent) { - document.detachEvent("onkeydown", keydownHandler); - document.detachEvent("onkeyup", keyupHandler); - } }; fillGrid = function() { var columnContainer = document.createElement("div"), column = document.createElement("div"), columnCount, columnWidth, docFragment = document.createDocumentFragment(), options = this.options, overlay = this.overlay, overlayHeight, overlayWidth, rowContainer = document.createElement("div"), row = document.createElement("div"), rowCount, rowHeight; rowContainer.classList.add(options.id + "-row-container"); columnContainer.classList.add(options.id + "-column-container"); overlay.appendChild(rowContainer); overlay.appendChild(columnContainer); row.classList.add(options.id + "__row"); column.classList.add(options.id + "__column"); rowContainer.appendChild(row); columnContainer.appendChild(column); overlay.style.display = "block"; overlay.top = "-9999px"; overlayHeight = overlay.scrollHeight; overlayWidth = overlay.scrollWidth; rowHeight = row.getBoundingClientRect().height; columnWidth = column.clientWidth; overlay.style.display = "none"; overlay.top = "0"; if (!rowHeight || !columnWidth) { return false; } rowCount = Math.floor(overlayHeight / rowHeight) - 1; columnCount = Math.floor(overlayWidth / columnWidth) - 2; while (rowCount--) { row = document.createElement("div"); row.classList.add(options.id + "__row"); docFragment.appendChild(row); } rowContainer.appendChild(docFragment); while (columnCount--) { column = document.createElement("div"); column.classList.add(options.id + "__column"); docFragment.appendChild(column); } columnContainer.appendChild(docFragment); }; keydownHandler = function(event) { var k, m, options = this.options; state = this.state; source = event.target.tagName.toLowerCase(); if (source == "input" || source == "textarea" || source == "select") { return true; } m = Helper.getKeyModifier(event, options.modifierKey); if (!m) { return true; } k = Helper.getKey(event); if (!k) { return true; } if (state.isKeyDown[k]) { return true; } state.isKeyDown[k] = true; switch (k) { case options.showGridKey: if (!state.overlayOn) { this.showOverlay(); state.overlayOn = true; } else if (state.overlayHold) { this.hideOverlay(); state.overlayOn = false; state.overlayHold = false; storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; case options.holdGridKey: if (state.overlayOn && !state.overlayHold) { state.overlayHold = true; storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; case options.foregroundKey: if (state.overlayOn) { if (this.overlay.style.zIndex === options.overlayZFG) { this.overlay.style.zIndex = options.overlayZBG; state.overlayZIndex = "B"; } else { this.overlay.style.zIndex = options.overlayZFG; state.overlayZIndex = "F"; } storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; case options.jumpGridsKey: + if (state.overlayOn && options.numberOfGrids > 1) { + this.overlay.classList.remove(options.classPrefix + state.gridNumber); + state.gridNumber += 1; + if (state.gridNumber > options.numberOfGrids) { + state.gridNumber = 1; + } + this.overlay.classList.add(options.classPrefix + state.gridNumber); + this.showOverlay(); + if (/webkit/.test(navigator.userAgent.toLowerCase())) { + Helper.forceRepaint(); + } + storage.write(options.storagePrefix + options.id, createStorageData.call(this)); + } break; } return true; }; keyupHandler = function(event) { var k, m = Helper.getKeyModifier(event), options = this.options, state = this.state; if (!m) { return true; } k = Helper.getKey(event); delete state.isKeyDown[k]; if (k && k == options.showGridKey && !state.overlayHold) { this.hideOverlay(); state.overlayOn = false; } return true; }; createStorageData = function() { var state = this.state; return { + gridNumber: state.gridNumber, overlayHold: state.overlayHold, overlayZIndex: state.overlayZIndex }; }; return Hashgrid; }(); window.Hashgrid = Hashgrid; if (typeof module != "undefined" && module.exports) module.exports = Hashgrid; })(window, document); \ No newline at end of file diff --git a/dist/javascripts/hashgrid.min.js b/dist/javascripts/hashgrid.min.js index 252a40c..b84da8c 100644 --- a/dist/javascripts/hashgrid.min.js +++ b/dist/javascripts/hashgrid.min.js @@ -1 +1 @@ -!function(a,b){var c=function(){function a(a,b){var c,d=Object.getOwnPropertyNames(b),e=d.length;for(c=0;e>c;c++)a[d[c]]=b[d[c]]}return{getKey:function(a){var b=!1,c=a.keyCode?a.keyCode:a.which;return b=13==c?"enter":String.fromCharCode(c).toLowerCase()},getKeyModifier:function(a,b){if(null===b)return!0;var c=!0;switch(b){case"ctrl":c=a.ctrlKey?a.ctrlKey:!1;break;case"alt":c=a.altKey?a.altKey:!1;break;case"shift":c=a.shiftKey?a.shiftKey:!1}return c},mergeObjects:function(b,c,d){return b||c||d?b&&"object"!=typeof b||c&&"object"!=typeof c||d&&"object"!=typeof d?{}:(c&&a(b,c),d&&a(b,d),b):{}},forceRepaint:function(){var a=b.styleSheets[0];try{a.addRule(".xxxxxx","position: relative"),a.removeRule(a.rules.length-1)}catch(c){}}}}();"undefined"!=typeof module&&module.exports&&(module.exports=c);var d=function(){function a(){}return a.prototype.read=function(a){var c,d=b.cookie.split(";"),e=0,f=d.length;for(a+="=";f>e;e++){for(c=d[e];" "===c.charAt(0);)c=c.substring(1,c.length);if(0===c.indexOf(a))return JSON.parse(c.substring(a.length,c.length))}return null},a.prototype.write=function(a,c,d){var e,f="",g="";return d&&(e=new Date,e.setTime(e.getTime()+24*d*60*60*1e3),f="; expires="+e.toGMTString()),g=a+"="+JSON.stringify(c)+f+"; path=/",b.cookie=g,g},a.prototype.remove=function(a){var b=this.read(a);return b?(this.write(a,"",-1),b):null},a}();"undefined"!=typeof module&&module.exports&&(module.exports=d);var e=function(){function b(){this.storage=a.sessionStorage}return b.prototype.read=function(a){var b=this.storage.getItem(a);return b?JSON.parse(b):null},b.prototype.write=function(a,b){return this.storage.setItem(a,JSON.stringify(b)),b},b.prototype.remove=function(a){var b=this.read(a);return b?(this.storage.removeItem(a),b):null},b}();if("undefined"!=typeof module&&module.exports&&(module.exports=e),"undefined"!=typeof module&&module.exports)var e=require("./sessionStorage"),d=require("./cookieStorage");var f=function(){return this.hasSessionStorage()?new e:new d};if(f.prototype.hasSessionStorage=function(){try{var b=a.sessionStorage,c="some value";return b.setItem(c,c),b.removeItem(c),!0}catch(d){return!1}},"undefined"!=typeof module&&module.exports&&(module.exports=f),"undefined"!=typeof module&&module.exports)var f=require("./storage"),c=require("./helper");var g=function(){function a(a){var b={id:"hashgrid",modifierKey:null,showGridKey:"g",holdGridKey:"h",foregroundKey:"f",jumpGridsKey:"j",numberOfGrids:1,classPrefix:"hashgrid",storagePrefix:"hashgrid"},d={overlayZBG:"-1",overlayZFG:"9999"};this.options=c.mergeObjects(b,a,d),this.state={},this.state.overlayHold=!1,this.state.overlayOn=!1,this.state.overlayZIndex="B",this.state.isKeyDown={},this.init()}var d=new f;return a.prototype.init=function(){var a;this.overlay=b.createElement("div"),this.overlay.id=this.options.id,this.overlay.style.display="none",this.overlay.style.pointerEvents="none",this.overlay.style.height=b.body.scrollHeight+"px","auto"===this.overlay.style.zIndex&&(this.overlay.style.zIndex=this.overlayZBackground),b.body.insertBefore(this.overlay,b.body.firstChild),b.addEventListener?(b.addEventListener("keydown",keydownHandler.bind(this),!1),b.addEventListener("keyup",keyupHandler.bind(this),!1)):b.attachEvent&&(b.attachEvent("onkeydown",keydownHandler.bind(this)),b.attachEvent("onkeyup",keyupHandler.bind(this))),fillGrid.call(this),a=d.read(this.options.storagePrefix+this.options.id),a&&(a.overlayHold&&(this.overlay.style.display="block",this.state.overlayOn=!0,this.state.overlayHold=!0),a.overlayZIndex&&("B"===a.overlayZIndex?this.overlay.style.zIndex=this.options.overlayZBG:"F"===a.overlayZIndex&&(this.overlay.style.zIndex=this.options.overlayZFG)))},a.prototype.showOverlay=function(){this.overlay.style.display="block",this.state.overlayOn=!0},a.prototype.hideOverlay=function(){this.overlay.style.display="none",this.state.overlayOn=!1},a.prototype.destroy=function(){this.overlay.remove(),b.removeEventListener?(b.removeEventListener("keydown",keydownHandler,!1),b.removeEventListener("keyup",keyupHandler,!1)):b.detachEvent&&(b.detachEvent("onkeydown",keydownHandler),b.detachEvent("onkeyup",keyupHandler))},fillGrid=function(){var a,c,d,e,f,g,h=b.createElement("div"),i=b.createElement("div"),j=b.createDocumentFragment(),k=this.options,l=this.overlay,m=b.createElement("div"),n=b.createElement("div");if(m.classList.add(k.id+"-row-container"),h.classList.add(k.id+"-column-container"),l.appendChild(m),l.appendChild(h),n.classList.add(k.id+"__row"),i.classList.add(k.id+"__column"),m.appendChild(n),h.appendChild(i),l.style.display="block",l.top="-9999px",d=l.scrollHeight,e=l.scrollWidth,g=n.getBoundingClientRect().height,c=i.clientWidth,l.style.display="none",l.top="0",!g||!c)return!1;for(f=Math.floor(d/g)-1,a=Math.floor(e/c)-2;f--;)n=b.createElement("div"),n.classList.add(k.id+"__row"),j.appendChild(n);for(m.appendChild(j);a--;)i=b.createElement("div"),i.classList.add(k.id+"__column"),j.appendChild(i);h.appendChild(j)},keydownHandler=function(a){var b,e,f=this.options;if(state=this.state,source=a.target.tagName.toLowerCase(),"input"==source||"textarea"==source||"select"==source)return!0;if(e=c.getKeyModifier(a,f.modifierKey),!e)return!0;if(b=c.getKey(a),!b)return!0;if(state.isKeyDown[b])return!0;switch(state.isKeyDown[b]=!0,b){case f.showGridKey:state.overlayOn?state.overlayHold&&(this.hideOverlay(),state.overlayOn=!1,state.overlayHold=!1,d.write(f.storagePrefix+f.id,createStorageData.call(this))):(this.showOverlay(),state.overlayOn=!0);break;case f.holdGridKey:state.overlayOn&&!state.overlayHold&&(state.overlayHold=!0,d.write(f.storagePrefix+f.id,createStorageData.call(this)));break;case f.foregroundKey:state.overlayOn&&(this.overlay.style.zIndex===f.overlayZFG?(this.overlay.style.zIndex=f.overlayZBG,state.overlayZIndex="B"):(this.overlay.style.zIndex=f.overlayZFG,state.overlayZIndex="F"),d.write(f.storagePrefix+f.id,createStorageData.call(this)));break;case f.jumpGridsKey:}return!0},keyupHandler=function(a){var b,d=c.getKeyModifier(a),e=this.options,f=this.state;return d?(b=c.getKey(a),delete f.isKeyDown[b],b&&b==e.showGridKey&&!f.overlayHold&&(this.hideOverlay(),f.overlayOn=!1),!0):!0},createStorageData=function(){var a=this.state;return{overlayHold:a.overlayHold,overlayZIndex:a.overlayZIndex}},a}();a.Hashgrid=g,"undefined"!=typeof module&&module.exports&&(module.exports=g)}(window,document); \ No newline at end of file +!function(a,b){var c=function(){function a(a,b){var c,d=Object.getOwnPropertyNames(b),e=d.length;for(c=0;e>c;c++)a[d[c]]=b[d[c]]}return{getKey:function(a){var b=!1,c=a.keyCode?a.keyCode:a.which;return b=13==c?"enter":String.fromCharCode(c).toLowerCase()},getKeyModifier:function(a,b){if(null===b)return!0;var c=!0;switch(b){case"ctrl":c=a.ctrlKey?a.ctrlKey:!1;break;case"alt":c=a.altKey?a.altKey:!1;break;case"shift":c=a.shiftKey?a.shiftKey:!1}return c},mergeObjects:function(b,c,d){return b||c||d?b&&"object"!=typeof b||c&&"object"!=typeof c||d&&"object"!=typeof d?{}:(c&&a(b,c),d&&a(b,d),b):{}},forceRepaint:function(){var a=b.styleSheets[0];try{a.addRule(".xxxxxx","position: relative"),a.removeRule(a.rules.length-1)}catch(c){}}}}();"undefined"!=typeof module&&module.exports&&(module.exports=c);var d=function(){function a(){}return a.prototype.read=function(a){var c,d=b.cookie.split(";"),e=0,f=d.length;for(a+="=";f>e;e++){for(c=d[e];" "===c.charAt(0);)c=c.substring(1,c.length);if(0===c.indexOf(a))return JSON.parse(c.substring(a.length,c.length))}return null},a.prototype.write=function(a,c,d){var e,f="",g="";return d&&(e=new Date,e.setTime(e.getTime()+24*d*60*60*1e3),f="; expires="+e.toGMTString()),g=a+"="+JSON.stringify(c)+f+"; path=/",b.cookie=g,g},a.prototype.remove=function(a){var b=this.read(a);return b?(this.write(a,"",-1),b):null},a}();"undefined"!=typeof module&&module.exports&&(module.exports=d);var e=function(){function b(){this.storage=a.sessionStorage}return b.prototype.read=function(a){var b=this.storage.getItem(a);return b?JSON.parse(b):null},b.prototype.write=function(a,b){return this.storage.setItem(a,JSON.stringify(b)),b},b.prototype.remove=function(a){var b=this.read(a);return b?(this.storage.removeItem(a),b):null},b}();if("undefined"!=typeof module&&module.exports&&(module.exports=e),"undefined"!=typeof module&&module.exports)var e=require("./sessionStorage"),d=require("./cookieStorage");var f=function(){return this.hasSessionStorage()?new e:new d};if(f.prototype.hasSessionStorage=function(){try{var b=a.sessionStorage,c="some value";return b.setItem(c,c),b.removeItem(c),!0}catch(d){return!1}},"undefined"!=typeof module&&module.exports&&(module.exports=f),"undefined"!=typeof module&&module.exports)var f=require("./storage"),c=require("./helper");var g=function(){function a(a){var b={id:"hashgrid",modifierKey:null,showGridKey:"g",holdGridKey:"h",foregroundKey:"f",jumpGridsKey:"j",numberOfGrids:1,classPrefix:"hashgrid",storagePrefix:"hashgrid"},d={overlayZBG:"-1",overlayZFG:"9999"};this.options=c.mergeObjects(b,a,d),this.state={},this.state.overlayHold=!1,this.state.overlayOn=!1,this.state.overlayZIndex="B",this.state.isKeyDown={},this.state.gridNumber=1,this.init()}var d=new f;return a.prototype.init=function(){var a;this.overlay=b.createElement("div"),this.overlay.id=this.options.id,this.overlay.classList.add(this.options.classPrefix+this.state.gridNumber),this.overlay.style.display="none",this.overlay.style.pointerEvents="none",this.overlay.style.height=b.body.scrollHeight+"px","auto"===this.overlay.style.zIndex&&(this.overlay.style.zIndex=this.overlayZBackground),b.body.insertBefore(this.overlay,b.body.firstChild),b.addEventListener?(b.addEventListener("keydown",keydownHandler.bind(this),!1),b.addEventListener("keyup",keyupHandler.bind(this),!1)):b.attachEvent&&(b.attachEvent("onkeydown",keydownHandler.bind(this)),b.attachEvent("onkeyup",keyupHandler.bind(this))),fillGrid.call(this),a=d.read(this.options.storagePrefix+this.options.id),a&&(a.gridNumber&&(this.overlay.classList.remove(this.options.classPrefix+this.state.gridNumber),this.overlay.classList.add(this.options.classPrefix+a.gridNumber),this.state.gridNumber=a.gridNumber),a.overlayHold&&(this.overlay.style.display="block",this.state.overlayOn=!0,this.state.overlayHold=!0),a.overlayZIndex&&("B"===a.overlayZIndex?this.overlay.style.zIndex=this.options.overlayZBG:"F"===a.overlayZIndex&&(this.overlay.style.zIndex=this.options.overlayZFG)))},a.prototype.showOverlay=function(){this.overlay.style.display="block",this.state.overlayOn=!0},a.prototype.hideOverlay=function(){this.overlay.style.display="none",this.state.overlayOn=!1},a.prototype.destroy=function(){this.overlay.remove()},fillGrid=function(){var a,c,d,e,f,g,h=b.createElement("div"),i=b.createElement("div"),j=b.createDocumentFragment(),k=this.options,l=this.overlay,m=b.createElement("div"),n=b.createElement("div");if(m.classList.add(k.id+"-row-container"),h.classList.add(k.id+"-column-container"),l.appendChild(m),l.appendChild(h),n.classList.add(k.id+"__row"),i.classList.add(k.id+"__column"),m.appendChild(n),h.appendChild(i),l.style.display="block",l.top="-9999px",d=l.scrollHeight,e=l.scrollWidth,g=n.getBoundingClientRect().height,c=i.clientWidth,l.style.display="none",l.top="0",!g||!c)return!1;for(f=Math.floor(d/g)-1,a=Math.floor(e/c)-2;f--;)n=b.createElement("div"),n.classList.add(k.id+"__row"),j.appendChild(n);for(m.appendChild(j);a--;)i=b.createElement("div"),i.classList.add(k.id+"__column"),j.appendChild(i);h.appendChild(j)},keydownHandler=function(a){var b,e,f=this.options;if(state=this.state,source=a.target.tagName.toLowerCase(),"input"==source||"textarea"==source||"select"==source)return!0;if(e=c.getKeyModifier(a,f.modifierKey),!e)return!0;if(b=c.getKey(a),!b)return!0;if(state.isKeyDown[b])return!0;switch(state.isKeyDown[b]=!0,b){case f.showGridKey:state.overlayOn?state.overlayHold&&(this.hideOverlay(),state.overlayOn=!1,state.overlayHold=!1,d.write(f.storagePrefix+f.id,createStorageData.call(this))):(this.showOverlay(),state.overlayOn=!0);break;case f.holdGridKey:state.overlayOn&&!state.overlayHold&&(state.overlayHold=!0,d.write(f.storagePrefix+f.id,createStorageData.call(this)));break;case f.foregroundKey:state.overlayOn&&(this.overlay.style.zIndex===f.overlayZFG?(this.overlay.style.zIndex=f.overlayZBG,state.overlayZIndex="B"):(this.overlay.style.zIndex=f.overlayZFG,state.overlayZIndex="F"),d.write(f.storagePrefix+f.id,createStorageData.call(this)));break;case f.jumpGridsKey:state.overlayOn&&f.numberOfGrids>1&&(this.overlay.classList.remove(f.classPrefix+state.gridNumber),state.gridNumber+=1,state.gridNumber>f.numberOfGrids&&(state.gridNumber=1),this.overlay.classList.add(f.classPrefix+state.gridNumber),this.showOverlay(),/webkit/.test(navigator.userAgent.toLowerCase())&&c.forceRepaint(),d.write(f.storagePrefix+f.id,createStorageData.call(this)))}return!0},keyupHandler=function(a){var b,d=c.getKeyModifier(a),e=this.options,f=this.state;return d?(b=c.getKey(a),delete f.isKeyDown[b],b&&b==e.showGridKey&&!f.overlayHold&&(this.hideOverlay(),f.overlayOn=!1),!0):!0},createStorageData=function(){var a=this.state;return{gridNumber:a.gridNumber,overlayHold:a.overlayHold,overlayZIndex:a.overlayZIndex}},a}();a.Hashgrid=g,"undefined"!=typeof module&&module.exports&&(module.exports=g)}(window,document); \ No newline at end of file diff --git a/index.htm b/index.htm index b58da97..9feb2b5 100644 --- a/index.htm +++ b/index.htm @@ -1,399 +1,449 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>#grid</title> <style type="text/css"> /* Putting inline rules here so the document can be downloaded with style */ body{ font-size: 1em; line-height: 1.25; font-family: Arial, sans-serif; background: White; color: DimGray; margin: 0; } #content{ font-size: 16px; line-height: 20px; position: relative; } #content{ width: 620px; margin: 0 auto; } #footer{ border-top: 1px dotted DarkGray; padding-top: 19px; } h1, h2{ color: Black; font-weight: normal; } h1{ font-size: 36px; line-height: 40px; margin: 40px 0 20px; padding-bottom: 19px; border-bottom: 1px dotted DarkGray; } h1 em{ font-style: normal; color: DarkGray; font-size: 16px; line-height: 20px; margin: 0 0 20px; } h2, h3{ font-size: 16px; font-weight: 700; line-height: 20px; margin: 0 0 20px; } h3{ font-weight: 300; } a:link, a:visited{ color: Black; text-decoration: none; padding: 0 2px; background-color: WhiteSmoke; border-bottom: 1px solid Gold; } a:focus{ outline: none; } a:focus, a:hover, a:active{ background-color: Khaki; border-bottom: 1px solid GoldenRod; } p, ul{ padding: 0; margin: 0 0 20px; } dl, ol{ padding: 0; margin: 0; } ul{ list-style: circle; } ol li{ margin-bottom: 20px; } dd{ margin: 0 0 20px 0; } del{ text-decoration: line-through; opacity: 0.75; } ins{ text-decoration: none; } code{ font-size: 14px; line-height: 1; } textarea{ font-family: 'Courier New', monospace; font-size: 14px; line-height: 20px; display: block; width: 600px; margin: 0 0 20px; padding: 0 0 0 15px; border: 0; color: Black; background: Gainsboro; border-left: 5px solid DarkGray; } #javascript-code{ height: 280px; } #css-code{ height: 1300px; } .summary em{ font-style: normal; position: absolute; color: DarkGray; right: 0; top: 18px; width: 140px; } .summary em span{ position: absolute; left: -9999px; } #download{ line-height: 60px; padding: 0 40px 0 15px; border-left: 5px solid DarkGray; background: Gainsboro; color: DimGray; } span.key{ color: Black; text-transform: uppercase; } </style> <!-- Set styles --> <style type="text/css"> /** * Grid */ #hashgrid{ /* Spreads the whole page by default, adjust to match your container */ /*width: 100%;*/ width: 980px; position: absolute; height: 100%; top: 0; left: 50%; margin-left: -490px; + overflow: hidden; } .hashgrid-column-container { position: absolute; height: 100%; width: 100%; top: 0; left: 0; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ .hashgrid__column{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-left: 19px; height: 100%; float: left; } - /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ .hashgrid__row{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } +/** +* Classes for multiple grids +* +* When using more than one grid, remember to set the numberOfGrids +* option when instantiating hashgrid. +* e.g. +* +* var hg = new Hashgrid({ +* numberOfGrids: 2 +* }); +*/ +#hashgrid.hashgrid2, +#hashgrid.hashgrid2 .hashgrid-column-container{ + /* Container width adjustments */ + padding: 0 160px; + width: 660px; +} + +#hashgrid.hashgrid2 .hashgrid__column{ + /* Vertical grid line colour for grid 2 */ + border-color: crimson; +} + + + + </style> </head> <body> <div id="content" role="main"> -<h1>#grid <em>v9</em></h1> +<h1>#grid <em>v10</em></h1> -<p class="summary"><em>Sat, 6 Oct 2012<span>:</span></em> This is a little tool we created for our <a href="http://analog.coop/">Analog&#160;holding&#160;page</a>. It inserts a <a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a> in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit <span class="key">g</span> on your keyboard.</p> +<p class="summary"><em>Mon, 30 Nov 2015<span>:</span></em> This is a little tool we created for our <a href="http://analog.coop/">Analog&#160;holding&#160;page</a>. It inserts a <a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a> in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit <span class="key">g</span> on your keyboard.</p> <h2>Download</h2> <p id="download"><a href="https://github.com/dotjay/hashgrid/downloads">Download #grid</a> from <a href="https://github.com/dotjay/hashgrid">GitHub</a></p> <h2 id="features">Features</h2> <ul> <li>Adaptable for all layout widths and alignments</li> <li>Adaptable for any vertical rhythm value</li> <li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li> <li>Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters</li> </ul> <p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p> <h2 id="installation">Installation</h2> <ol> <li><h3>Copy the <a href="https://github.com/dotjay/hashgrid/blob/v9/hashgrid.js">hashgrid.js</a> script to your project</h3></li> <li><h3>Add this script to your page(s) just before the closing <code>&#60;/body&#62;</code> tag</h3> <textarea id="javascript-code" cols="68" rows="14" readonly="readonly"> &#60;!-- Include the hashgrid script --&#62; &#60;script type="text/javascript" src="hashgrid.js"&#62;&#60;/script&#62; &#60;!-- Kick hashgrid into action --&#62; &#60;script type="text/javascript"&#62; var grid = new hashgrid({ numberOfGrids: 2 }); &#60;/script&#62;</textarea></li> <li><h3>Add the CSS to your page(s)</h3> <textarea id="css-code" cols="68" rows="64" readonly="readonly"> /** * Grid */ #hashgrid{ /* Spreads the whole page by default, adjust to match your container */ /*width: 100%;*/ width: 980px; position: absolute; height: 100%; top: 0; left: 50%; margin-left: -490px; + overflow: hidden; } .hashgrid-column-container { position: absolute; height: 100%; width: 100%; top: 0; left: 0; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ .hashgrid__column{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-left: 19px; height: 100%; float: left; } - /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ .hashgrid__row{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } +/** +* Classes for multiple grids +* +* When using more than one grid, remember to set the numberOfGrids +* option when instantiating hashgrid. +* e.g. +* +* var hg = new Hashgrid({ +* numberOfGrids: 2 +* }); +*/ +#hashgrid.hashgrid2, +#hashgrid.hashgrid2 .hashgrid-column-container{ + /* Container width adjustments */ + padding: 0 160px; + width: 660px; +} + +#hashgrid.hashgrid2 .hashgrid__column{ + /* Vertical grid line colour for grid 2 */ + border-color: crimson; +} </textarea></li> <li><h3>Modify #grid to suit your needs</h3> <p>The CSS and JavaScript is annotated to help you.</p></li> </ol> <h2 id="usage">Usage</h2> <p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p> <dl> <dt><span class="key">g</span></dt> <dd>Show the grid until you release.</dd> <dt><span class="key">g</span> + <span class="key">h</span></dt> <dd>Show and hold the grid (<span class="key">g</span> will remove it again).</dd> <dt><span class="key">g</span> + <span class="key">f</span></dt> <dd>Toggle the grid to the foreground and back. Pressing <span class="key">f</span> while the grid is held also works.</dd> <dt><span class="key">g</span> + <span class="key">j</span></dt> <dd>Jump to the next grid. Pressing <span class="key">j</span> while the grid is held also works.</dd> </dl> <p><em>N.B. Hashgrid remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page except in Chrome v4, Safari v4, Firefox v3.6, or more recent versions.</em></p> <h2 id="release-notes">Release Notes</h2> <dl> <dt>v10&#8201;&#8212;&#8201;30 Nov 2015</dt> <dd>jQuery is no longer required.</dd> <dt>v9&#8201;&#8212;&#8201;30 May 2013</dt> <dd>Minor release: Improved example usage to avoid conflicts.</dd> <dt>v8&#8201;&#8212;&#8201;6 Oct 2012</dt> <dd> <ul> <li>Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="http://www.tomarnold.de/">Tom Arnold</a>.</li> <li>Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="http://lynx.io/">Callum Macrae</a>.</li> <li>Fixes to cookie handling. Thanks to <a href="http://loonypandora.co.uk/">James Aitken</a>.</li> <li>Optimisations.</li> </ul> </dd> <dt>v7&#8201;&#8212;&#8201;11 Jun 2011</dt> <dd>Minor release: Updated license references.</dd> <dt>v6&#8201;&#8212;&#8201;10 Jun 2011</dt> <dd>Minor release: Optimisations (thanks to <a href="http://andrewjaswa.com/">Andrew Jaswa</a> for contributions), and now released under an Apache License.</dd> <dt>v5&#8201;&#8212;&#8201;3 Nov 2010</dt> <dd> <ul> <li>Vertical grid lines can now be set using CSS&#8230; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution.</li> <li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li> <li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback.</li> </ul> </dd> <dt>v4&#8201;&#8212;&#8201;29 Mar 2010</dt> <dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd> <dt>v3&#8201;&#8212;&#8201;22 Feb 2010</dt> <dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd> <dt>v2&#8201;&#8212;&#8201;2 Feb 2010</dt> <dd> <ul> <li>Keys are now more easily configured (see top of hashgrid.js).</li> <li>Fixed crash when using with disabled CSS.</li> <li>Renamed the GridOverlay object to hashgrid.</li> </ul> </dd> <dt>v1&#8201;&#8212;&#8201;21 Dec 2009</dt> <dd>First release.</dd> </dl> <h2 id="known-issues">Known Issues</h2> <ul> <li><del>IE 8: Fully functional, but the default <span class="key">ALT</span> + <span class="key">G</span> + <span class="key">ENTER</span> shortcut puts IE into full screen mode. Hit <span class="key">ALT</span> + <span class="key">ENTER</span> to toggle full screen mode off again.</del><ins datetime="2010-02-22"> The default keyboard shortcuts have been changed.</ins></li> <li>IE 6: The grid is always in the foreground.</li> <li>Opera 9/10: Using <span class="key">CTRL</span> or <span class="key">ALT</span> as a modifier key will not work due to different key handling by the browser.</li> </ul> <h2 id="license">License</h2> <p>Copyright 2013 Analog Coop Limited</p> <p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br /><br /> <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a></p> <p>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.</p> <p>This essentially means that you&#8217;re free to copy, modify and distribute it for any project so long as you provide clear attribution to Analog Coop Limited. <a href="http://analog.coop/#talk-to-us">Contact us</a> if you need a different license.</p> <div id="footer" role="contentinfo"> <p>#grid is an <a href="http://analog.coop/">Analog</a> gig. It was conceived by <a href="http://jontangerine.com/">Jon Tan</a>, and built by <a href="http://accessibility.co.uk/">Jon Gibbins</a>, in cahoots with our <a href="http://analog.coop#is">fine friends</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p> </div> </div> <!-- Include the hashgrid script --> <script type="text/javascript" src="dist/javascripts/hashgrid.js"></script> <!-- Kick hashgrid into action --> <script> -var hg = new Hashgrid(); +var hg = new Hashgrid({ + numberOfGrids: 2 +}); </script> </body> </html> diff --git a/src/hashgrid.js b/src/hashgrid.js index 218ec41..63020e5 100644 --- a/src/hashgrid.js +++ b/src/hashgrid.js @@ -1,336 +1,370 @@ /** * hashgrid (vanilla version) * http://github.com/dotjay/hashgrid * Version 10, 25 Nov 2015 * Written by Jon Gibbins at Analog, http://analog.coop/ * * Contibutors: * Sean Coates, http://seancoates.com/ * Phil Dokas, http://jetless.org/ * Andrew Jaswa, http://andrewjaswa.com/ * * License: * http://www.apache.org/licenses/LICENSE-2.0.html * * // Using a basic #grid setup * var grid = new Hashgrid(); * * // Using #grid with a custom id (e.g. #mygrid) * var grid = new Hashgrid("mygrid"); * * // Using #grid with additional options * var grid = new hashgrid({ * id: "mygrid", // id for the grid container * modifierKey: "alt", // optional "ctrl", "alt" or "shift" * showGridKey: "s", // key to show the grid * holdGridKey: "enter", // key to hold the grid shown * foregroundKey: "f", // key to toggle foreground/background * jumpGridsKey: "d", // key to cycle through the grids * numberOfGrids: 2, // number of grids * classPrefix: "mygrid", // prefix for rows and columns * storagePrefix: "mygrid" // prefix for storage label * }); */ if (typeof module!="undefined" && module.exports) { var Storage = require("./storage"); var Helper = require("./helper"); } var Hashgrid = (function() { var storage = new Storage(); // Constructor function Hashgrid(customOptions) { var defaultOptions = { id: "hashgrid", // id for the grid container modifierKey: null, // optional "ctrl", "alt" or "shift" showGridKey: "g", // key to show the grid holdGridKey: "h", // key to hold the grid shown foregroundKey: "f", // key to toggle foreground/background jumpGridsKey: "j", // key to cycle through the grids numberOfGrids: 1, // number of grids classPrefix: "hashgrid", // prefix for rows and columns storagePrefix: "hashgrid" // prefix for storage label }, privateOptions = { overlayZBG: "-1", overlayZFG: "9999" }; // Apply options this.options = Helper.mergeObjects(defaultOptions, customOptions, privateOptions); this.state = {}; this.state.overlayHold = false; this.state.overlayOn = false; this.state.overlayZIndex = "B"; this.state.isKeyDown = {}; + this.state.gridNumber = 1; this.init(); } // Instance methods Hashgrid.prototype.init = function() { var storageData; // Create overlay, hidden before adding to DOM this.overlay = document.createElement("div"); this.overlay.id = this.options.id; + this.overlay.classList.add(this.options.classPrefix + this.state.gridNumber); this.overlay.style.display = "none"; this.overlay.style.pointerEvents = "none"; this.overlay.style.height = document.body.scrollHeight + "px"; // Unless a custom z-index is set, ensure the overlay will be behind everything if(this.overlay.style.zIndex === "auto") { this.overlay.style.zIndex = this.overlayZBackground; } // Prepend overlay to body document.body.insertBefore(this.overlay, document.body.firstChild); // Add keyboard events listener + // TODO: Find a way to add event handler that is bindable and removable if(document.addEventListener) { document.addEventListener("keydown", keydownHandler.bind(this), false); document.addEventListener("keyup", keyupHandler.bind(this), false); } else if(document.attachEvent){ document.attachEvent("onkeydown", keydownHandler.bind(this)); document.attachEvent("onkeyup", keyupHandler.bind(this)); } fillGrid.call(this); storageData = storage.read(this.options.storagePrefix + this.options.id); + // TODO: Improve storage and state management if(storageData) { + if(storageData.gridNumber) { + this.overlay.classList.remove(this.options.classPrefix + this.state.gridNumber); + this.overlay.classList.add(this.options.classPrefix + storageData.gridNumber); + this.state.gridNumber = storageData.gridNumber; + } + if(storageData.overlayHold) { this.overlay.style.display = "block"; this.state.overlayOn = true; this.state.overlayHold = true; } if(storageData.overlayZIndex) { if(storageData.overlayZIndex === "B"){ this.overlay.style.zIndex = this.options.overlayZBG; } else if(storageData.overlayZIndex === "F"){ this.overlay.style.zIndex = this.options.overlayZFG; } } } }; Hashgrid.prototype.showOverlay = function() { this.overlay.style.display = "block"; this.state.overlayOn = true; }; Hashgrid.prototype.hideOverlay = function() { this.overlay.style.display = "none"; this.state.overlayOn = false; }; Hashgrid.prototype.destroy = function() { this.overlay.remove(); - // Remove keyboard events listener - if(document.removeEventListener) { - document.removeEventListener("keydown", keydownHandler, false); - document.removeEventListener("keyup", keyupHandler, false); - } - else if(document.detachEvent){ - document.detachEvent("onkeydown", keydownHandler); - document.detachEvent("onkeyup", keyupHandler); - } + // Remove keyboard events listener (these does not work) + //if(document.removeEventListener) { + //document.removeEventListener("keydown", keydownHandler, false); + //document.removeEventListener("keyup", keyupHandler, false); + //} + //else if(document.detachEvent){ + //document.detachEvent("onkeydown", keydownHandler); + //document.detachEvent("onkeyup", keyupHandler); + //} }; // Helper functions fillGrid = function() { var columnContainer = document.createElement("div"), column = document.createElement("div"), columnCount, columnWidth, docFragment = document.createDocumentFragment(), options = this.options, overlay = this.overlay, overlayHeight, overlayWidth, rowContainer = document.createElement("div"), row = document.createElement("div"), rowCount, rowHeight; // Row and column container rowContainer.classList.add(options.id + "-row-container"); columnContainer.classList.add(options.id + "-column-container"); overlay.appendChild(rowContainer); overlay.appendChild(columnContainer); // First row and column row.classList.add(options.id + "__row"); column.classList.add(options.id + "__column"); rowContainer.appendChild(row); columnContainer.appendChild(column); // Display temporarily to get row and column size overlay.style.display = "block"; overlay.top = "-9999px"; overlayHeight = overlay.scrollHeight; overlayWidth = overlay.scrollWidth; rowHeight = row.getBoundingClientRect().height; // height + border columnWidth = column.clientWidth; // Hide it again overlay.style.display = "none"; overlay.top = "0"; if(!rowHeight || !columnWidth) { return false; } // Calculate rows and columns needed rowCount = Math.floor(overlayHeight / rowHeight) - 1; columnCount = Math.floor(overlayWidth / columnWidth) - 2; // Fill them in while(rowCount--) { row = document.createElement("div"); row.classList.add(options.id + "__row"); docFragment.appendChild(row); } rowContainer.appendChild(docFragment); while(columnCount--) { column = document.createElement("div"); column.classList.add(options.id + "__column"); docFragment.appendChild(column); } columnContainer.appendChild(docFragment); }; keydownHandler = function(event) { var k, m, options = this.options; state = this.state; source = event.target.tagName.toLowerCase(); if ((source == 'input') || (source == 'textarea') || (source == 'select')) { return true; } m = Helper.getKeyModifier(event, options.modifierKey); if(!m) { return true; } k = Helper.getKey(event); if(!k) { return true; } if(state.isKeyDown[k]) { return true; } state.isKeyDown[k] = true; switch(k) { case options.showGridKey: if(!state.overlayOn) { this.showOverlay(); state.overlayOn = true; } else if(state.overlayHold) { this.hideOverlay(); state.overlayOn = false; state.overlayHold = false; + storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; case options.holdGridKey: if(state.overlayOn && !state.overlayHold) { state.overlayHold = true; + storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; case options.foregroundKey: + // TODO: Turn into instance method if(state.overlayOn) { if(this.overlay.style.zIndex === options.overlayZFG) { this.overlay.style.zIndex = options.overlayZBG; state.overlayZIndex = "B"; } else { this.overlay.style.zIndex = options.overlayZFG; state.overlayZIndex = "F"; } + storage.write(options.storagePrefix + options.id, createStorageData.call(this)); } break; case options.jumpGridsKey: + // TODO: Turn into instance method + if(state.overlayOn && options.numberOfGrids > 1) { + // Cycle through available grids + this.overlay.classList.remove(options.classPrefix + state.gridNumber); + state.gridNumber += 1; + + if(state.gridNumber > options.numberOfGrids) { + state.gridNumber = 1; + } + + this.overlay.classList.add(options.classPrefix + state.gridNumber); + this.showOverlay(); + + if (/webkit/.test( navigator.userAgent.toLowerCase() )) { + Helper.forceRepaint(); + } + + storage.write(options.storagePrefix + options.id, createStorageData.call(this)); + } break; } return true; }; keyupHandler = function(event) { var k, m = Helper.getKeyModifier(event), options = this.options, state = this.state; if (!m) { return true; } k = Helper.getKey(event); delete state.isKeyDown[k]; if (k && (k == options.showGridKey) && !state.overlayHold) { this.hideOverlay(); state.overlayOn = false; } return true; }; createStorageData = function() { var state = this.state; return { + gridNumber: state.gridNumber, overlayHold: state.overlayHold, overlayZIndex: state.overlayZIndex }; }; return Hashgrid; })(); window.Hashgrid = Hashgrid; if (typeof module!="undefined" && module.exports) module.exports = Hashgrid;
dotjay/hashgrid
61e67993eef1cbd32881ab6526dea3dedd9d546a
Change local storage to session storage
diff --git a/src/localStorage.js b/src/sessionStorage.js similarity index 61% rename from src/localStorage.js rename to src/sessionStorage.js index 0a716ce..fafe32c 100644 --- a/src/localStorage.js +++ b/src/sessionStorage.js @@ -1,39 +1,39 @@ -var LocalStorage = (function() { +var SessionStorage = (function() { - function LocalStorage() { - this.storage = window.localStorage; + function SessionStorage() { + this.storage = window.sessionStorage; } - LocalStorage.prototype.read = function(dataLabel) { + SessionStorage.prototype.read = function(dataLabel) { var dataValue = this.storage.getItem(dataLabel); if(dataValue) { return JSON.parse(dataValue); } else { return null; } }; - LocalStorage.prototype.write = function(dataLabel, dataValue) { + SessionStorage.prototype.write = function(dataLabel, dataValue) { this.storage.setItem(dataLabel, JSON.stringify(dataValue)); return dataValue; }; - LocalStorage.prototype.remove = function(dataLabel) { + SessionStorage.prototype.remove = function(dataLabel) { var removedDataValue = this.read(dataLabel); if(removedDataValue) { this.storage.removeItem(dataLabel); return removedDataValue; } else { return null; } }; - return LocalStorage; + return SessionStorage; })(); -if (typeof module!="undefined" && module.exports) module.exports = LocalStorage; +if (typeof module!="undefined" && module.exports) module.exports = SessionStorage; diff --git a/src/storage.js b/src/storage.js index f78ab8c..119d89e 100644 --- a/src/storage.js +++ b/src/storage.js @@ -1,35 +1,35 @@ /* * This is just a proxy for storage function * Ideally, local storage is used, * cookie storage is provided only as fallback */ if (typeof module!='undefined' && module.exports) { - var LocalStorage = require("./localStorage"); + var SessionStorage = require("./sessionStorage"); var CookieStorage = require("./cookieStorage"); } var Storage = function() { - if(this.hasLocalStorage()) { - return new LocalStorage(); + if(this.hasSessionStorage()) { + return new SessionStorage(); } else { return new CookieStorage(); } }; -Storage.prototype.hasLocalStorage = function() { +Storage.prototype.hasSessionStorage = function() { try { - var storage = window.localStorage, + var storage = window.sessionStorage, someData = "some value"; storage.setItem(someData, someData); storage.removeItem(someData); return true; } catch(e) { return false; } }; if (typeof module!="undefined" && module.exports) module.exports = Storage; diff --git a/tests/localStorage.js b/tests/sessionStorage.js similarity index 76% rename from tests/localStorage.js rename to tests/sessionStorage.js index f555b20..59780cc 100644 --- a/tests/localStorage.js +++ b/tests/sessionStorage.js @@ -1,22 +1,22 @@ var tape = require("tape"); -var LocalStorage = require("../src/localStorage"); +var SessionStorage = require("../src/sessionStorage"); -tape("Local Storage module", function(assert) { - var storage = new LocalStorage(); +tape("Session Storage module", function(assert) { + var storage = new SessionStorage(); var dataLabel = "label"; var dataValue = "value"; - window.localStorage.clear(); + window.sessionStorage.clear(); assert.equal(storage.read(dataLabel), null, "Data reading returns null if data value is not set"); assert.ok(storage.write(dataLabel, dataValue), "Data writing returns written value"); assert.equal(storage.read(dataLabel), dataValue, "Data writing sets valid data value"); assert.equal(storage.remove(dataLabel), dataValue, "Data removal returns removed value"); assert.equal(storage.read(dataLabel), null, "Data reading returns null after data value is removed"); assert.end(); });
dotjay/hashgrid
df055a17bd674662d84641436e3f2304e632b954
Add grunt tasks
diff --git a/Gruntfile.js b/Gruntfile.js new file mode 100644 index 0000000..ad2e51e --- /dev/null +++ b/Gruntfile.js @@ -0,0 +1,14 @@ +module.exports = function(grunt) { + + require("load-grunt-config")(grunt, { + data: { + srcDir: "src", + buildDir: "dist", + tempDir: "temp" + } + }); + + grunt.registerTask("build", ["clean:dist", "uglify"]); + grunt.registerTask("dev", ["build", "watch"]); + grunt.registerTask("default", "build"); +}; diff --git a/dist/javascripts/hashgrid.js b/dist/javascripts/hashgrid.js new file mode 100644 index 0000000..d9c09d3 --- /dev/null +++ b/dist/javascripts/hashgrid.js @@ -0,0 +1,347 @@ +(function(window, document) { + var Helper = function() { + function copyObjectProperties(target, source) { + var properties = Object.getOwnPropertyNames(source); + var propertyLength = properties.length; + var idx; + for (idx = 0; idx < propertyLength; idx++) { + target[properties[idx]] = source[properties[idx]]; + } + } + return { + getKey: function(event) { + var k = false, c = event.keyCode ? event.keyCode : event.which; + if (c == 13) k = "enter"; else k = String.fromCharCode(c).toLowerCase(); + return k; + }, + getKeyModifier: function(event, modifierOption) { + if (modifierOption === null) return true; + var m = true; + switch (modifierOption) { + case "ctrl": + m = event.ctrlKey ? event.ctrlKey : false; + break; + + case "alt": + m = event.altKey ? event.altKey : false; + break; + + case "shift": + m = event.shiftKey ? event.shiftKey : false; + break; + } + return m; + }, + mergeObjects: function(mergedObject, obj1, obj2) { + if (!mergedObject && !obj1 && !obj2) { + return {}; + } else if (mergedObject && typeof mergedObject !== "object" || obj1 && typeof obj1 !== "object" || obj2 && typeof obj2 !== "object") { + return {}; + } + if (obj1) { + copyObjectProperties(mergedObject, obj1); + } + if (obj2) { + copyObjectProperties(mergedObject, obj2); + } + return mergedObject; + }, + forceRepaint: function() { + var ss = document.styleSheets[0]; + try { + ss.addRule(".xxxxxx", "position: relative"); + ss.removeRule(ss.rules.length - 1); + } catch (e) {} + } + }; + }(); + if (typeof module != "undefined" && module.exports) module.exports = Helper; + var CookieStorage = function() { + function CookieStorage() {} + CookieStorage.prototype.read = function(cookieLabel) { + var cookieCrumb, cookieArray = document.cookie.split(";"), i = 0, cookieCrumbCount = cookieArray.length; + cookieLabel = cookieLabel + "="; + for (;i < cookieCrumbCount; i++) { + cookieCrumb = cookieArray[i]; + while (cookieCrumb.charAt(0) === " ") { + cookieCrumb = cookieCrumb.substring(1, cookieCrumb.length); + } + if (cookieCrumb.indexOf(cookieLabel) === 0) { + return JSON.parse(cookieCrumb.substring(cookieLabel.length, cookieCrumb.length)); + } + } + return null; + }; + CookieStorage.prototype.write = function(cookieLabel, cookieValue, expirationDay) { + var date, cookieExpires = "", toBeWritten = ""; + if (expirationDay) { + date = new Date(); + date.setTime(date.getTime() + expirationDay * 24 * 60 * 60 * 1e3); + cookieExpires = "; expires=" + date.toGMTString(); + } + toBeWritten = cookieLabel + "=" + JSON.stringify(cookieValue) + cookieExpires + "; path=/"; + document.cookie = toBeWritten; + return toBeWritten; + }; + CookieStorage.prototype.remove = function(cookieLabel) { + var removedCookieValue = this.read(cookieLabel); + if (removedCookieValue) { + this.write(cookieLabel, "", -1); + return removedCookieValue; + } else { + return null; + } + }; + return CookieStorage; + }(); + if (typeof module != "undefined" && module.exports) module.exports = CookieStorage; + var LocalStorage = function() { + function LocalStorage() { + this.storage = window.localStorage; + } + LocalStorage.prototype.read = function(dataLabel) { + var dataValue = this.storage.getItem(dataLabel); + if (dataValue) { + return JSON.parse(dataValue); + } else { + return null; + } + }; + LocalStorage.prototype.write = function(dataLabel, dataValue) { + this.storage.setItem(dataLabel, JSON.stringify(dataValue)); + return dataValue; + }; + LocalStorage.prototype.remove = function(dataLabel) { + var removedDataValue = this.read(dataLabel); + if (removedDataValue) { + this.storage.removeItem(dataLabel); + return removedDataValue; + } else { + return null; + } + }; + return LocalStorage; + }(); + if (typeof module != "undefined" && module.exports) module.exports = LocalStorage; + if (typeof module != "undefined" && module.exports) { + var LocalStorage = require("./localStorage"); + var CookieStorage = require("./cookieStorage"); + } + var Storage = function() { + if (this.hasLocalStorage()) { + return new LocalStorage(); + } else { + return new CookieStorage(); + } + }; + Storage.prototype.hasLocalStorage = function() { + try { + var storage = window.localStorage, someData = "some value"; + storage.setItem(someData, someData); + storage.removeItem(someData); + return true; + } catch (e) { + return false; + } + }; + if (typeof module != "undefined" && module.exports) module.exports = Storage; + if (typeof module != "undefined" && module.exports) { + var Storage = require("./storage"); + var Helper = require("./helper"); + } + var Hashgrid = function() { + var storage = new Storage(); + function Hashgrid(customOptions) { + var defaultOptions = { + id: "hashgrid", + modifierKey: null, + showGridKey: "g", + holdGridKey: "h", + foregroundKey: "f", + jumpGridsKey: "j", + numberOfGrids: 1, + classPrefix: "hashgrid", + storagePrefix: "hashgrid" + }, privateOptions = { + overlayZBG: "-1", + overlayZFG: "9999" + }; + this.options = Helper.mergeObjects(defaultOptions, customOptions, privateOptions); + this.state = {}; + this.state.overlayHold = false; + this.state.overlayOn = false; + this.state.overlayZIndex = "B"; + this.state.isKeyDown = {}; + this.init(); + } + Hashgrid.prototype.init = function() { + var storageData; + this.overlay = document.createElement("div"); + this.overlay.id = this.options.id; + this.overlay.style.display = "none"; + this.overlay.style.pointerEvents = "none"; + this.overlay.style.height = document.body.scrollHeight + "px"; + if (this.overlay.style.zIndex === "auto") { + this.overlay.style.zIndex = this.overlayZBackground; + } + document.body.insertBefore(this.overlay, document.body.firstChild); + if (document.addEventListener) { + document.addEventListener("keydown", keydownHandler.bind(this), false); + document.addEventListener("keyup", keyupHandler.bind(this), false); + } else if (document.attachEvent) { + document.attachEvent("onkeydown", keydownHandler.bind(this)); + document.attachEvent("onkeyup", keyupHandler.bind(this)); + } + fillGrid.call(this); + storageData = storage.read(this.options.storagePrefix + this.options.id); + if (storageData) { + if (storageData.overlayHold) { + this.overlay.style.display = "block"; + this.state.overlayOn = true; + this.state.overlayHold = true; + } + if (storageData.overlayZIndex) { + if (storageData.overlayZIndex === "B") { + this.overlay.style.zIndex = this.options.overlayZBG; + } else if (storageData.overlayZIndex === "F") { + this.overlay.style.zIndex = this.options.overlayZFG; + } + } + } + }; + Hashgrid.prototype.showOverlay = function() { + this.overlay.style.display = "block"; + this.state.overlayOn = true; + }; + Hashgrid.prototype.hideOverlay = function() { + this.overlay.style.display = "none"; + this.state.overlayOn = false; + }; + Hashgrid.prototype.destroy = function() { + this.overlay.remove(); + if (document.removeEventListener) { + document.removeEventListener("keydown", keydownHandler, false); + document.removeEventListener("keyup", keyupHandler, false); + } else if (document.detachEvent) { + document.detachEvent("onkeydown", keydownHandler); + document.detachEvent("onkeyup", keyupHandler); + } + }; + fillGrid = function() { + var columnContainer = document.createElement("div"), column = document.createElement("div"), columnCount, columnWidth, docFragment = document.createDocumentFragment(), options = this.options, overlay = this.overlay, overlayHeight, overlayWidth, rowContainer = document.createElement("div"), row = document.createElement("div"), rowCount, rowHeight; + rowContainer.classList.add(options.id + "-row-container"); + columnContainer.classList.add(options.id + "-column-container"); + overlay.appendChild(rowContainer); + overlay.appendChild(columnContainer); + row.classList.add(options.id + "__row"); + column.classList.add(options.id + "__column"); + rowContainer.appendChild(row); + columnContainer.appendChild(column); + overlay.style.display = "block"; + overlay.top = "-9999px"; + overlayHeight = overlay.scrollHeight; + overlayWidth = overlay.scrollWidth; + rowHeight = row.getBoundingClientRect().height; + columnWidth = column.clientWidth; + overlay.style.display = "none"; + overlay.top = "0"; + if (!rowHeight || !columnWidth) { + return false; + } + rowCount = Math.floor(overlayHeight / rowHeight) - 1; + columnCount = Math.floor(overlayWidth / columnWidth) - 2; + while (rowCount--) { + row = document.createElement("div"); + row.classList.add(options.id + "__row"); + docFragment.appendChild(row); + } + rowContainer.appendChild(docFragment); + while (columnCount--) { + column = document.createElement("div"); + column.classList.add(options.id + "__column"); + docFragment.appendChild(column); + } + columnContainer.appendChild(docFragment); + }; + keydownHandler = function(event) { + var k, m, options = this.options; + state = this.state; + source = event.target.tagName.toLowerCase(); + if (source == "input" || source == "textarea" || source == "select") { + return true; + } + m = Helper.getKeyModifier(event, options.modifierKey); + if (!m) { + return true; + } + k = Helper.getKey(event); + if (!k) { + return true; + } + if (state.isKeyDown[k]) { + return true; + } + state.isKeyDown[k] = true; + switch (k) { + case options.showGridKey: + if (!state.overlayOn) { + this.showOverlay(); + state.overlayOn = true; + } else if (state.overlayHold) { + this.hideOverlay(); + state.overlayOn = false; + state.overlayHold = false; + storage.write(options.storagePrefix + options.id, createStorageData.call(this)); + } + break; + + case options.holdGridKey: + if (state.overlayOn && !state.overlayHold) { + state.overlayHold = true; + storage.write(options.storagePrefix + options.id, createStorageData.call(this)); + } + break; + + case options.foregroundKey: + if (state.overlayOn) { + if (this.overlay.style.zIndex === options.overlayZFG) { + this.overlay.style.zIndex = options.overlayZBG; + state.overlayZIndex = "B"; + } else { + this.overlay.style.zIndex = options.overlayZFG; + state.overlayZIndex = "F"; + } + storage.write(options.storagePrefix + options.id, createStorageData.call(this)); + } + break; + + case options.jumpGridsKey: + break; + } + return true; + }; + keyupHandler = function(event) { + var k, m = Helper.getKeyModifier(event), options = this.options, state = this.state; + if (!m) { + return true; + } + k = Helper.getKey(event); + delete state.isKeyDown[k]; + if (k && k == options.showGridKey && !state.overlayHold) { + this.hideOverlay(); + state.overlayOn = false; + } + return true; + }; + createStorageData = function() { + var state = this.state; + return { + overlayHold: state.overlayHold, + overlayZIndex: state.overlayZIndex + }; + }; + return Hashgrid; + }(); + window.Hashgrid = Hashgrid; + if (typeof module != "undefined" && module.exports) module.exports = Hashgrid; +})(window, document); \ No newline at end of file diff --git a/dist/javascripts/hashgrid.min.js b/dist/javascripts/hashgrid.min.js new file mode 100644 index 0000000..f77e71f --- /dev/null +++ b/dist/javascripts/hashgrid.min.js @@ -0,0 +1 @@ +!function(a,b){var c=function(){function a(a,b){var c,d=Object.getOwnPropertyNames(b),e=d.length;for(c=0;e>c;c++)a[d[c]]=b[d[c]]}return{getKey:function(a){var b=!1,c=a.keyCode?a.keyCode:a.which;return b=13==c?"enter":String.fromCharCode(c).toLowerCase()},getKeyModifier:function(a,b){if(null===b)return!0;var c=!0;switch(b){case"ctrl":c=a.ctrlKey?a.ctrlKey:!1;break;case"alt":c=a.altKey?a.altKey:!1;break;case"shift":c=a.shiftKey?a.shiftKey:!1}return c},mergeObjects:function(b,c,d){return b||c||d?b&&"object"!=typeof b||c&&"object"!=typeof c||d&&"object"!=typeof d?{}:(c&&a(b,c),d&&a(b,d),b):{}},forceRepaint:function(){var a=b.styleSheets[0];try{a.addRule(".xxxxxx","position: relative"),a.removeRule(a.rules.length-1)}catch(c){}}}}();"undefined"!=typeof module&&module.exports&&(module.exports=c);var d=function(){function a(){}return a.prototype.read=function(a){var c,d=b.cookie.split(";"),e=0,f=d.length;for(a+="=";f>e;e++){for(c=d[e];" "===c.charAt(0);)c=c.substring(1,c.length);if(0===c.indexOf(a))return JSON.parse(c.substring(a.length,c.length))}return null},a.prototype.write=function(a,c,d){var e,f="",g="";return d&&(e=new Date,e.setTime(e.getTime()+24*d*60*60*1e3),f="; expires="+e.toGMTString()),g=a+"="+JSON.stringify(c)+f+"; path=/",b.cookie=g,g},a.prototype.remove=function(a){var b=this.read(a);return b?(this.write(a,"",-1),b):null},a}();"undefined"!=typeof module&&module.exports&&(module.exports=d);var e=function(){function b(){this.storage=a.localStorage}return b.prototype.read=function(a){var b=this.storage.getItem(a);return b?JSON.parse(b):null},b.prototype.write=function(a,b){return this.storage.setItem(a,JSON.stringify(b)),b},b.prototype.remove=function(a){var b=this.read(a);return b?(this.storage.removeItem(a),b):null},b}();if("undefined"!=typeof module&&module.exports&&(module.exports=e),"undefined"!=typeof module&&module.exports)var e=require("./localStorage"),d=require("./cookieStorage");var f=function(){return this.hasLocalStorage()?new e:new d};if(f.prototype.hasLocalStorage=function(){try{var b=a.localStorage,c="some value";return b.setItem(c,c),b.removeItem(c),!0}catch(d){return!1}},"undefined"!=typeof module&&module.exports&&(module.exports=f),"undefined"!=typeof module&&module.exports)var f=require("./storage"),c=require("./helper");var g=function(){function a(a){var b={id:"hashgrid",modifierKey:null,showGridKey:"g",holdGridKey:"h",foregroundKey:"f",jumpGridsKey:"j",numberOfGrids:1,classPrefix:"hashgrid",storagePrefix:"hashgrid"},d={overlayZBG:"-1",overlayZFG:"9999"};this.options=c.mergeObjects(b,a,d),this.state={},this.state.overlayHold=!1,this.state.overlayOn=!1,this.state.overlayZIndex="B",this.state.isKeyDown={},this.init()}var d=new f;return a.prototype.init=function(){var a;this.overlay=b.createElement("div"),this.overlay.id=this.options.id,this.overlay.style.display="none",this.overlay.style.pointerEvents="none",this.overlay.style.height=b.body.scrollHeight+"px","auto"===this.overlay.style.zIndex&&(this.overlay.style.zIndex=this.overlayZBackground),b.body.insertBefore(this.overlay,b.body.firstChild),b.addEventListener?(b.addEventListener("keydown",keydownHandler.bind(this),!1),b.addEventListener("keyup",keyupHandler.bind(this),!1)):b.attachEvent&&(b.attachEvent("onkeydown",keydownHandler.bind(this)),b.attachEvent("onkeyup",keyupHandler.bind(this))),fillGrid.call(this),a=d.read(this.options.storagePrefix+this.options.id),a&&(a.overlayHold&&(this.overlay.style.display="block",this.state.overlayOn=!0,this.state.overlayHold=!0),a.overlayZIndex&&("B"===a.overlayZIndex?this.overlay.style.zIndex=this.options.overlayZBG:"F"===a.overlayZIndex&&(this.overlay.style.zIndex=this.options.overlayZFG)))},a.prototype.showOverlay=function(){this.overlay.style.display="block",this.state.overlayOn=!0},a.prototype.hideOverlay=function(){this.overlay.style.display="none",this.state.overlayOn=!1},a.prototype.destroy=function(){this.overlay.remove(),b.removeEventListener?(b.removeEventListener("keydown",keydownHandler,!1),b.removeEventListener("keyup",keyupHandler,!1)):b.detachEvent&&(b.detachEvent("onkeydown",keydownHandler),b.detachEvent("onkeyup",keyupHandler))},fillGrid=function(){var a,c,d,e,f,g,h=b.createElement("div"),i=b.createElement("div"),j=b.createDocumentFragment(),k=this.options,l=this.overlay,m=b.createElement("div"),n=b.createElement("div");if(m.classList.add(k.id+"-row-container"),h.classList.add(k.id+"-column-container"),l.appendChild(m),l.appendChild(h),n.classList.add(k.id+"__row"),i.classList.add(k.id+"__column"),m.appendChild(n),h.appendChild(i),l.style.display="block",l.top="-9999px",d=l.scrollHeight,e=l.scrollWidth,g=n.getBoundingClientRect().height,c=i.clientWidth,l.style.display="none",l.top="0",!g||!c)return!1;for(f=Math.floor(d/g)-1,a=Math.floor(e/c)-2;f--;)n=b.createElement("div"),n.classList.add(k.id+"__row"),j.appendChild(n);for(m.appendChild(j);a--;)i=b.createElement("div"),i.classList.add(k.id+"__column"),j.appendChild(i);h.appendChild(j)},keydownHandler=function(a){var b,e,f=this.options;if(state=this.state,source=a.target.tagName.toLowerCase(),"input"==source||"textarea"==source||"select"==source)return!0;if(e=c.getKeyModifier(a,f.modifierKey),!e)return!0;if(b=c.getKey(a),!b)return!0;if(state.isKeyDown[b])return!0;switch(state.isKeyDown[b]=!0,b){case f.showGridKey:state.overlayOn?state.overlayHold&&(this.hideOverlay(),state.overlayOn=!1,state.overlayHold=!1,d.write(f.storagePrefix+f.id,createStorageData.call(this))):(this.showOverlay(),state.overlayOn=!0);break;case f.holdGridKey:state.overlayOn&&!state.overlayHold&&(state.overlayHold=!0,d.write(f.storagePrefix+f.id,createStorageData.call(this)));break;case f.foregroundKey:state.overlayOn&&(this.overlay.style.zIndex===f.overlayZFG?(this.overlay.style.zIndex=f.overlayZBG,state.overlayZIndex="B"):(this.overlay.style.zIndex=f.overlayZFG,state.overlayZIndex="F"),d.write(f.storagePrefix+f.id,createStorageData.call(this)));break;case f.jumpGridsKey:}return!0},keyupHandler=function(a){var b,d=c.getKeyModifier(a),e=this.options,f=this.state;return d?(b=c.getKey(a),delete f.isKeyDown[b],b&&b==e.showGridKey&&!f.overlayHold&&(this.hideOverlay(),f.overlayOn=!1),!0):!0},createStorageData=function(){var a=this.state;return{overlayHold:a.overlayHold,overlayZIndex:a.overlayZIndex}},a}();a.Hashgrid=g,"undefined"!=typeof module&&module.exports&&(module.exports=g)}(window,document); \ No newline at end of file diff --git a/grunt/clean.js b/grunt/clean.js new file mode 100644 index 0000000..991ed3b --- /dev/null +++ b/grunt/clean.js @@ -0,0 +1,8 @@ +module.exports = { + dist: { + src: ["<%= buildDir %>"] + }, + temp: { + src: ["<%= tempDir %>"] + } +}; diff --git a/grunt/uglify.js b/grunt/uglify.js new file mode 100644 index 0000000..9d4f557 --- /dev/null +++ b/grunt/uglify.js @@ -0,0 +1,39 @@ +srcFiles = [ + "<%= srcDir %>/helper.js", + "<%= srcDir %>/cookieStorage.js", + "<%= srcDir %>/localStorage.js", + "<%= srcDir %>/storage.js", + "<%= srcDir %>/hashgrid.js" +]; + +module.exports = { + options: { + enclose: { + "window": "window", + "document": "document" + } + }, + + normal: { + options: { + mangle: false, + compress: false, + beautify: true + }, + + files: { + "<%= buildDir %>/javascripts/hashgrid.js": srcFiles + } + }, + + min: { + options: { + mangle: true, + compress: true + }, + + files: { + "<%= buildDir %>/javascripts/hashgrid.min.js": srcFiles + } + } +}; diff --git a/grunt/watch.js b/grunt/watch.js new file mode 100644 index 0000000..a95286d --- /dev/null +++ b/grunt/watch.js @@ -0,0 +1,11 @@ +module.exports = { + javascripts: { + files: [ + "<%= srcDir %>/**/*.js" + ], + + tasks: [ + "build" + ] + } +}; diff --git a/package.json b/package.json index 2959e42..4a70fd8 100644 --- a/package.json +++ b/package.json @@ -1,29 +1,30 @@ { "name": "hashgrid", "version": "9.0.0", "description": "A little tool that inserts a layout grid in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background.", "main": "hashgrid.js", "scripts": { "test": "./node_modules/.bin/hihat tests/*.js -p tap-dev-tool" }, "repository": { "type": "git", "url": "git+https://github.com/widatama/hashgrid.git" }, "author": "", "license": "Apache-2.0", "bugs": { "url": "https://github.com/widatama/hashgrid/issues" }, "homepage": "https://github.com/widatama/hashgrid#readme", "devDependencies": { "grunt": "^0.4.5", "grunt-contrib-clean": "^0.7.0", + "grunt-contrib-concat": "^0.5.1", "grunt-contrib-uglify": "^0.11.0", "grunt-contrib-watch": "^0.6.1", "hihat": "^2.5.0", "load-grunt-config": "^0.19.0", "tap-dev-tool": "^1.3.0", "tape": "^4.2.2" } }
dotjay/hashgrid
c7ba235ca1bac32d0ad3041ebacaa96ba49014e3
Create Hashgrid module
diff --git a/index.htm b/index.htm index fe74c54..ec0b288 100644 --- a/index.htm +++ b/index.htm @@ -1,473 +1,439 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>#grid</title> <style type="text/css"> /* Putting inline rules here so the document can be downloaded with style */ body{ font-size: 1em; line-height: 1.25; font-family: Arial, sans-serif; background: White; color: DimGray; margin: 0; -padding: 0 20px; } #content{ font-size: 16px; line-height: 20px; position: relative; } #content{ width: 620px; margin: 0 auto; } #footer{ border-top: 1px dotted DarkGray; padding-top: 19px; } h1, h2{ color: Black; font-weight: normal; } h1{ font-size: 36px; line-height: 40px; margin: 40px 0 20px; padding-bottom: 19px; border-bottom: 1px dotted DarkGray; } h1 em{ font-style: normal; color: DarkGray; font-size: 16px; line-height: 20px; margin: 0 0 20px; } h2, h3{ font-size: 16px; font-weight: 700; line-height: 20px; margin: 0 0 20px; } h3{ font-weight: 300; } a:link, a:visited{ color: Black; text-decoration: none; padding: 0 2px; background-color: WhiteSmoke; border-bottom: 1px solid Gold; } a:focus{ outline: none; } a:focus, a:hover, a:active{ background-color: Khaki; border-bottom: 1px solid GoldenRod; } p, ul{ padding: 0; margin: 0 0 20px; } dl, ol{ padding: 0; margin: 0; } ul{ list-style: circle; } ol li{ margin-bottom: 20px; } dd{ margin: 0 0 20px 0; } del{ text-decoration: line-through; opacity: 0.75; } ins{ text-decoration: none; } code{ font-size: 14px; line-height: 1; } textarea{ font-family: 'Courier New', monospace; font-size: 14px; line-height: 20px; display: block; width: 600px; margin: 0 0 20px; padding: 0 0 0 15px; border: 0; color: Black; background: Gainsboro; border-left: 5px solid DarkGray; } #javascript-code{ height: 280px; } #css-code{ height: 1300px; } .summary em{ font-style: normal; position: absolute; color: DarkGray; right: 0; top: 18px; width: 140px; } .summary em span{ position: absolute; left: -9999px; } #download{ line-height: 60px; padding: 0 40px 0 15px; border-left: 5px solid DarkGray; background: Gainsboro; color: DimGray; } span.key{ color: Black; text-transform: uppercase; } </style> <!-- Set styles --> <style type="text/css"> /** * Grid */ -#grid{ - - /* Dimensions - same width as your grid with gutters */ - width: 980px; - - /* Grid (left-aligned) - position: absolute; - top: 0; - left: 0; - */ - - /* Grid (centered) */ - position: absolute; - top: 0; - left: 50%; - margin-left: -490px; +#hashgrid{ + /* Spreads the whole page by default, adjust to match your container */ + /*width: 100%;*/ + width: 980px; + position: absolute; + height: 100%; + top: 0; + left: 50%; + margin-left: -490px; +} +.hashgrid-column-container { + position: absolute; + height: 100%; + width: 100%; + top: 0; + left: 0; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ -#grid div.vert{ - - width: 139px; - border: solid darkturquoise; - border-width: 0 1px; - margin-right: 19px; - -} - -#grid div.vert.first-line{ - - margin-left: 19px; - +.hashgrid__column{ + width: 139px; + border: solid darkturquoise; + border-width: 0 1px; + margin-left: 19px; + height: 100%; + float: left; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ -#grid div.horiz{ - - /* 20px line height */ - height: 19px; - border-bottom: 1px dotted darkgray; - margin: 0; - padding: 0; - -} - -/** -* Classes for multiple grids -* -* When using more than one grid, remember to set the numberOfGrids -* option in the hashgrid.js file. -*/ -#grid.grid-1 div.vert{ - - /* Vertical grid line colour for grid 1 */ - border-color: darkturquoise; - -} -#grid.grid-2{ - - /* Adjustments */ - padding: 0 160px; - width: 660px; - -} -#grid.grid-2 div.vert{ - - /* Vertical grid line colour for grid 2 */ - border-color: crimson; - +.hashgrid__row{ + /* 20px line height */ + height: 19px; + border-bottom: 1px dotted darkgray; + margin: 0; + padding: 0; } </style> </head> <body> <div id="content" role="main"> <h1>#grid <em>v9</em></h1> <p class="summary"><em>Sat, 6 Oct 2012<span>:</span></em> This is a little tool we created for our <a href="http://analog.coop/">Analog&#160;holding&#160;page</a>. It inserts a <a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a> in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit <span class="key">G</span> on your keyboard.</p> <h2>Download</h2> <p id="download"><a href="https://github.com/dotjay/hashgrid/downloads">Download #grid</a> from <a href="https://github.com/dotjay/hashgrid">GitHub</a></p> <h2 id="features">Features</h2> <ul> <li>Adaptable for all layout widths and alignments</li> <li>Adaptable for any vertical rhythm value</li> <li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li> <li>Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters</li> </ul> <p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p> <h2 id="installation">Installation</h2> <ol> <li><h3>Copy the <a href="https://github.com/dotjay/hashgrid/blob/v9/hashgrid.js">hashgrid.js</a> script to your project</h3></li> <li><h3>Add the script to your page(s) just inside the <code>&#60;/body&#62;</code> tag</h3> <textarea id="javascript-code" cols="68" rows="14" readonly="readonly"> &#60;!-- Grab latest version of jQuery --&#62; &#60;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"&#62; &#60;/script&#62; &#60;!-- Include the hashgrid script --&#62; &#60;script type="text/javascript" src="hashgrid.js"&#62;&#60;/script&#62; &#60;!-- Kick hashgrid into action --&#62; &#60;script type="text/javascript"&#62; var grid = new hashgrid({ numberOfGrids: 2 }); &#60;/script&#62;</textarea></li> <li><h3>Add the CSS to your page(s)</h3> <textarea id="css-code" cols="68" rows="64" readonly="readonly"> /** * Grid */ #grid{ /* Dimensions - same width as your grid with gutters */ width: 980px; /* Grid (left-aligned) position: absolute; top: 0; left: 0; */ /* Grid (centered) */ position: absolute; top: 0; left: 50%; margin-left: -490px; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ #grid div.vert{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-right: 19px; } #grid div.vert.first-line{ margin-left: 19px; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ #grid div.horiz{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * -* When using more than one grid, remember to set the numberOfGrids +* When using more than one grid, remember to set the numberOfGrids * option in the hashgrid.js file. */ #grid.grid-1 div.vert{ /* Vertical grid line colour for grid 1 */ border-color: darkturquoise; } #grid.grid-2{ /* Adjustments */ padding: 0 160px; width: 660px; } #grid.grid-2 div.vert{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </textarea></li> <li><h3>Modify #grid to suit your needs</h3> <p>The CSS and JavaScript is annotated to help you.</p></li> </ol> <h2 id="usage">Usage</h2> <p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p> <dl> <dt><span class="key">G</span></dt> <dd>Show the grid until you release.</dd> <dt><span class="key">G</span> + <span class="key">H</span></dt> <dd>Show and hold the grid (<span class="key">G</span> will remove it again).</dd> <dt><span class="key">G</span> + <span class="key">F</span></dt> <dd>Toggle the grid to the foreground and back. Pressing <span class="key">F</span> while the grid is held also works.</dd> <dt><span class="key">G</span> + <span class="key">J</span></dt> <dd>Jump to the next grid. Pressing <span class="key">J</span> while the grid is held also works.</dd> </dl> <p><em>N.B. A cookie conveniently remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page except in Chrome v4, Safari v4, Firefox v3.6, or more recent versions.</em></p> <h2 id="release-notes">Release Notes</h2> <dl> <dt>v9&#8201;&#8212;&#8201;30 May 2013</dt> <dd>Minor release: Improved example usage to avoid conflicts.</dd> <dt>v8&#8201;&#8212;&#8201;6 Oct 2012</dt> <dd> <ul> <li>Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="http://www.tomarnold.de/">Tom Arnold</a>.</li> <li>Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="http://lynx.io/">Callum Macrae</a>.</li> <li>Fixes to cookie handling. Thanks to <a href="http://loonypandora.co.uk/">James Aitken</a>.</li> <li>Optimisations.</li> </ul> </dd> <dt>v7&#8201;&#8212;&#8201;11 Jun 2011</dt> <dd>Minor release: Updated license references.</dd> <dt>v6&#8201;&#8212;&#8201;10 Jun 2011</dt> <dd>Minor release: Optimisations (thanks to <a href="http://andrewjaswa.com/">Andrew Jaswa</a> for contributions), and now released under an Apache License.</dd> <dt>v5&#8201;&#8212;&#8201;3 Nov 2010</dt> <dd> <ul> <li>Vertical grid lines can now be set using CSS&#8230; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution.</li> <li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li> <li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback.</li> </ul> </dd> <dt>v4&#8201;&#8212;&#8201;29 Mar 2010</dt> <dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd> <dt>v3&#8201;&#8212;&#8201;22 Feb 2010</dt> <dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd> <dt>v2&#8201;&#8212;&#8201;2 Feb 2010</dt> <dd> <ul> <li>Keys are now more easily configured (see top of hashgrid.js).</li> <li>Fixed crash when using with disabled CSS.</li> <li>Renamed the GridOverlay object to hashgrid.</li> </ul> </dd> <dt>v1&#8201;&#8212;&#8201;21 Dec 2009</dt> <dd>First release.</dd> </dl> <h2 id="known-issues">Known Issues</h2> <ul> <li><del>IE 8: Fully functional, but the default <span class="key">ALT</span> + <span class="key">G</span> + <span class="key">ENTER</span> shortcut puts IE into full screen mode. Hit <span class="key">ALT</span> + <span class="key">ENTER</span> to toggle full screen mode off again.</del><ins datetime="2010-02-22"> The default keyboard shortcuts have been changed.</ins></li> <li>IE 6: The grid is always in the foreground.</li> <li>Opera 9/10: Using <span class="key">CTRL</span> or <span class="key">ALT</span> as a modifier key will not work due to different key handling by the browser.</li> </ul> <h2 id="license">License</h2> <p>Copyright 2013 Analog Coop Limited</p> <p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br /><br /> <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a></p> <p>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.</p> <p>This essentially means that you&#8217;re free to copy, modify and distribute it for any project so long as you provide clear attribution to Analog Coop Limited. <a href="http://analog.coop/#talk-to-us">Contact us</a> if you need a different license.</p> <div id="footer" role="contentinfo"> <p>#grid is an <a href="http://analog.coop/">Analog</a> gig. It was conceived by <a href="http://jontangerine.com/">Jon Tan</a>, and built by <a href="http://accessibility.co.uk/">Jon Gibbins</a>, in cahoots with our <a href="http://analog.coop#is">fine friends</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p> </div> </div> -<!-- Grab latest version of jQuery --> -<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script> - <!-- Include the hashgrid script --> -<script type="text/javascript" src="hashgrid.js"></script> +<script type="text/javascript" src="dist/javascripts/hashgrid.js"></script> + +<script> + hg = new Hashgrid(); +</script> <!-- Kick hashgrid into action --> <script type="text/javascript"> var grid = new hashgrid({ numberOfGrids: 2 }); </script> </body> </html> diff --git a/src/hashgrid.js b/src/hashgrid.js new file mode 100644 index 0000000..218ec41 --- /dev/null +++ b/src/hashgrid.js @@ -0,0 +1,336 @@ +/** + * hashgrid (vanilla version) + * http://github.com/dotjay/hashgrid + * Version 10, 25 Nov 2015 + * Written by Jon Gibbins at Analog, http://analog.coop/ + * + * Contibutors: + * Sean Coates, http://seancoates.com/ + * Phil Dokas, http://jetless.org/ + * Andrew Jaswa, http://andrewjaswa.com/ + * + * License: + * http://www.apache.org/licenses/LICENSE-2.0.html + * + * // Using a basic #grid setup + * var grid = new Hashgrid(); + * + * // Using #grid with a custom id (e.g. #mygrid) + * var grid = new Hashgrid("mygrid"); + * + * // Using #grid with additional options + * var grid = new hashgrid({ + * id: "mygrid", // id for the grid container + * modifierKey: "alt", // optional "ctrl", "alt" or "shift" + * showGridKey: "s", // key to show the grid + * holdGridKey: "enter", // key to hold the grid shown + * foregroundKey: "f", // key to toggle foreground/background + * jumpGridsKey: "d", // key to cycle through the grids + * numberOfGrids: 2, // number of grids + * classPrefix: "mygrid", // prefix for rows and columns + * storagePrefix: "mygrid" // prefix for storage label + * }); + */ + +if (typeof module!="undefined" && module.exports) { + var Storage = require("./storage"); + var Helper = require("./helper"); +} + +var Hashgrid = (function() { + + var storage = new Storage(); + + // Constructor + function Hashgrid(customOptions) { + + var + defaultOptions = { + id: "hashgrid", // id for the grid container + modifierKey: null, // optional "ctrl", "alt" or "shift" + showGridKey: "g", // key to show the grid + holdGridKey: "h", // key to hold the grid shown + foregroundKey: "f", // key to toggle foreground/background + jumpGridsKey: "j", // key to cycle through the grids + numberOfGrids: 1, // number of grids + classPrefix: "hashgrid", // prefix for rows and columns + storagePrefix: "hashgrid" // prefix for storage label + }, + privateOptions = { + overlayZBG: "-1", + overlayZFG: "9999" + }; + + // Apply options + this.options = Helper.mergeObjects(defaultOptions, customOptions, privateOptions); + + this.state = {}; + + this.state.overlayHold = false; + this.state.overlayOn = false; + this.state.overlayZIndex = "B"; + this.state.isKeyDown = {}; + + this.init(); + } + + + // Instance methods + + Hashgrid.prototype.init = function() { + var storageData; + + // Create overlay, hidden before adding to DOM + this.overlay = document.createElement("div"); + this.overlay.id = this.options.id; + this.overlay.style.display = "none"; + this.overlay.style.pointerEvents = "none"; + this.overlay.style.height = document.body.scrollHeight + "px"; + + // Unless a custom z-index is set, ensure the overlay will be behind everything + if(this.overlay.style.zIndex === "auto") { + this.overlay.style.zIndex = this.overlayZBackground; + } + + // Prepend overlay to body + document.body.insertBefore(this.overlay, document.body.firstChild); + + // Add keyboard events listener + if(document.addEventListener) { + document.addEventListener("keydown", keydownHandler.bind(this), false); + document.addEventListener("keyup", keyupHandler.bind(this), false); + } + else if(document.attachEvent){ + document.attachEvent("onkeydown", keydownHandler.bind(this)); + document.attachEvent("onkeyup", keyupHandler.bind(this)); + } + + fillGrid.call(this); + + storageData = storage.read(this.options.storagePrefix + this.options.id); + + if(storageData) { + if(storageData.overlayHold) { + this.overlay.style.display = "block"; + this.state.overlayOn = true; + this.state.overlayHold = true; + } + + if(storageData.overlayZIndex) { + if(storageData.overlayZIndex === "B"){ + this.overlay.style.zIndex = this.options.overlayZBG; + } + else if(storageData.overlayZIndex === "F"){ + this.overlay.style.zIndex = this.options.overlayZFG; + } + } + } + + }; + + Hashgrid.prototype.showOverlay = function() { + this.overlay.style.display = "block"; + this.state.overlayOn = true; + }; + + Hashgrid.prototype.hideOverlay = function() { + this.overlay.style.display = "none"; + this.state.overlayOn = false; + }; + + Hashgrid.prototype.destroy = function() { + this.overlay.remove(); + + // Remove keyboard events listener + if(document.removeEventListener) { + document.removeEventListener("keydown", keydownHandler, false); + document.removeEventListener("keyup", keyupHandler, false); + } + else if(document.detachEvent){ + document.detachEvent("onkeydown", keydownHandler); + document.detachEvent("onkeyup", keyupHandler); + } + }; + + + // Helper functions + + fillGrid = function() { + var + columnContainer = document.createElement("div"), + column = document.createElement("div"), + columnCount, + columnWidth, + docFragment = document.createDocumentFragment(), + options = this.options, + overlay = this.overlay, + overlayHeight, + overlayWidth, + rowContainer = document.createElement("div"), + row = document.createElement("div"), + rowCount, + rowHeight; + + // Row and column container + rowContainer.classList.add(options.id + "-row-container"); + columnContainer.classList.add(options.id + "-column-container"); + + overlay.appendChild(rowContainer); + overlay.appendChild(columnContainer); + + + // First row and column + row.classList.add(options.id + "__row"); + column.classList.add(options.id + "__column"); + + rowContainer.appendChild(row); + columnContainer.appendChild(column); + + + // Display temporarily to get row and column size + overlay.style.display = "block"; + overlay.top = "-9999px"; + + overlayHeight = overlay.scrollHeight; + overlayWidth = overlay.scrollWidth; + rowHeight = row.getBoundingClientRect().height; // height + border + columnWidth = column.clientWidth; + + // Hide it again + overlay.style.display = "none"; + overlay.top = "0"; + + if(!rowHeight || !columnWidth) { + return false; + } + + // Calculate rows and columns needed + rowCount = Math.floor(overlayHeight / rowHeight) - 1; + columnCount = Math.floor(overlayWidth / columnWidth) - 2; + + // Fill them in + while(rowCount--) { + row = document.createElement("div"); + row.classList.add(options.id + "__row"); + + docFragment.appendChild(row); + } + + rowContainer.appendChild(docFragment); + + while(columnCount--) { + column = document.createElement("div"); + column.classList.add(options.id + "__column"); + + docFragment.appendChild(column); + } + + columnContainer.appendChild(docFragment); + }; + + keydownHandler = function(event) { + var + k, + m, + options = this.options; + state = this.state; + source = event.target.tagName.toLowerCase(); + + if ((source == 'input') || (source == 'textarea') || (source == 'select')) { + return true; + } + + m = Helper.getKeyModifier(event, options.modifierKey); + if(!m) { + return true; + } + + k = Helper.getKey(event); + if(!k) { + return true; + } + + if(state.isKeyDown[k]) { + return true; + } + + state.isKeyDown[k] = true; + + switch(k) { + case options.showGridKey: + if(!state.overlayOn) { + this.showOverlay(); + state.overlayOn = true; + } + else if(state.overlayHold) { + this.hideOverlay(); + state.overlayOn = false; + state.overlayHold = false; + storage.write(options.storagePrefix + options.id, createStorageData.call(this)); + } + break; + case options.holdGridKey: + if(state.overlayOn && !state.overlayHold) { + state.overlayHold = true; + storage.write(options.storagePrefix + options.id, createStorageData.call(this)); + } + break; + case options.foregroundKey: + if(state.overlayOn) { + if(this.overlay.style.zIndex === options.overlayZFG) { + this.overlay.style.zIndex = options.overlayZBG; + state.overlayZIndex = "B"; + } + else { + this.overlay.style.zIndex = options.overlayZFG; + state.overlayZIndex = "F"; + } + storage.write(options.storagePrefix + options.id, createStorageData.call(this)); + } + break; + case options.jumpGridsKey: + break; + } + + return true; + }; + + keyupHandler = function(event) { + var + k, + m = Helper.getKeyModifier(event), + options = this.options, + state = this.state; + + if (!m) { + return true; + } + + k = Helper.getKey(event); + + delete state.isKeyDown[k]; + + if (k && (k == options.showGridKey) && !state.overlayHold) { + this.hideOverlay(); + state.overlayOn = false; + } + + return true; + }; + + createStorageData = function() { + var state = this.state; + return { + overlayHold: state.overlayHold, + overlayZIndex: state.overlayZIndex + }; + }; + + return Hashgrid; + +})(); + + +window.Hashgrid = Hashgrid; + +if (typeof module!="undefined" && module.exports) module.exports = Hashgrid; diff --git a/tests/hashgrid.js b/tests/hashgrid.js new file mode 100644 index 0000000..efbc082 --- /dev/null +++ b/tests/hashgrid.js @@ -0,0 +1,35 @@ +var tape = require("tape"); +var Hashgrid = require("../src/hashgrid"); + +function setupDOM() { + document.body.style.height = "100px"; +} + +tape("Hashgrid module", function(assert) { + var hashgrid; + var hashgridOptions = { + id: "hashgrid" + }; + var hashgridEl; + + setupDOM(); + hashgrid = new Hashgrid(hashgridOptions); + hashgridEl = document.querySelector("#" + hashgridOptions.id); + + assert.ok(hashgridEl, "Hashgrid created"); + + hashgrid.showOverlay(); + + assert.equal(hashgridEl.style.display, "block", "Hashgrid shown"); + + hashgrid.hideOverlay(); + + assert.equal(hashgridEl.style.display, "none", "Hashgrid hidden"); + + hashgrid.destroy(); + hashgridEl = document.querySelector("#" + hashgridOptions.id); + + assert.notOk(hashgridEl, "Hashgrid destroyed"); + + assert.end(); +});
dotjay/hashgrid
f27e7b43a41b1aeaf14aeb4c5698a527c1f37f25
Create Helper module
diff --git a/src/helper.js b/src/helper.js new file mode 100644 index 0000000..83f560d --- /dev/null +++ b/src/helper.js @@ -0,0 +1,94 @@ + +var Helper = (function() { + + function copyObjectProperties(target, source) { + var properties = Object.getOwnPropertyNames(source); + var propertyLength = properties.length; + var idx; + + for(idx = 0; idx < propertyLength; idx++) { + target[properties[idx]] = source[properties[idx]]; + } + } + + + return { + + /* Keyboard event helpers */ + getKey: function(event) { + var k = false, c = (event.keyCode ? event.keyCode : event.which); + // Handle keywords + if (c == 13) k = 'enter'; + // Handle letters + else k = String.fromCharCode(c).toLowerCase(); + return k; + }, + + getKeyModifier: function(event, modifierOption) { + if (modifierOption === null) return true; // Bypass by default + var m = true; + switch(modifierOption) { + case 'ctrl': + m = (event.ctrlKey ? event.ctrlKey : false); + break; + + case 'alt': + m = (event.altKey ? event.altKey : false); + break; + + case 'shift': + m = (event.shiftKey ? event.shiftKey : false); + break; + } + return m; + }, + + /* + * Simple object merge + * - merge obj1 and obj2 to mergedResult + * - mergedResult, obj1 and obj2 can only contain primitives + * - obj2 is optional + */ + mergeObjects: function(mergedObject, obj1, obj2) { + + if(!mergedObject && !obj1 && !obj2) { + return {}; + } + else if( + (mergedObject && typeof(mergedObject) !== "object") || + (obj1 && typeof(obj1) !== "object") || + (obj2 && typeof(obj2) !== "object")) { + return {}; + } + + if(obj1) { + copyObjectProperties(mergedObject, obj1); + } + + if(obj2) { + copyObjectProperties(mergedObject, obj2); + } + + return mergedObject; + }, + + /** + * Forces a repaint (because WebKit has issues) + * http://www.sitepoint.com/forums/showthread.php?p=4538763 + * http://www.phpied.com/the-new-game-show-will-it-reflow/ + */ + forceRepaint: function() { + var ss = document.styleSheets[0]; + + try { + ss.addRule('.xxxxxx', 'position: relative'); + ss.removeRule(ss.rules.length - 1); + } + catch(e) {} + } + }; + +})(); + + +if (typeof module!="undefined" && module.exports) module.exports = Helper; diff --git a/tests/helper.js b/tests/helper.js new file mode 100644 index 0000000..e1a219b --- /dev/null +++ b/tests/helper.js @@ -0,0 +1,93 @@ +var tape = require("tape"); +var Helper = require("../src/helper"); + +function setupKeyboardEvent(keyCode, keyModifier) { + // So much for dispatching event, sigh + var kbdEvent = new KeyboardEvent("keydown"); + var initMethod = kbdEvent.initKeyboardEvent ? "initKeyboardEvent" : "initKeyEvent"; + + Object.defineProperty(kbdEvent, "keyCode", { + get: function() { + return this.keyCodeVal; + } + }); + + Object.defineProperty(kbdEvent, "which", { + get: function() { + return this.keyCodeVal; + } + }); + + if(keyModifier) { + Object.defineProperty(kbdEvent, keyModifier + "Key", { + get: function() { + return this.keyModifierVal; + } + }); + } + + kbdEvent[initMethod]( + "keydown", + true, + true, + window, + keyModifier === "ctrl" ? true : false, + keyModifier === "alt" ? true : false, + keyModifier === "shift" ? true : false, + keyModifier === "metaKey" ? true : false, + keyCode, + 0 + ); + + kbdEvent.keyCodeVal = keyCode; + kbdEvent.keyModifierVal = true; + + return kbdEvent; +} + +tape("Helper module", function(assert) { + var obj1 = { + a: 1, + b: 2 + }; + var obj2 = { + a: 2, + c: 3 + }; + var obj3 = { + a: 2, + b: 2, + c: 3 + }; + + var keyCode = "a"; + var keyModifier = "alt"; + + var kbdEvent = setupKeyboardEvent(keyCode.charCodeAt(0), keyModifier); + + assert.plan(2); + + assert.test("Object merge", function(assert) { + assert.plan(5); + + assert.deepEqual(Helper.mergeObjects(), {}, "Returns an empty object when called without any arguments"); + assert.deepEqual(Helper.mergeObjects("string"), {}, "Returns an empty object when one of the arguments is not an object"); + assert.deepEqual(Helper.mergeObjects(obj1), obj1, "Returns the only available object for merge"); + assert.deepEqual(Helper.mergeObjects(obj1, obj2), obj3, "Two objects merged properly"); + assert.deepEqual(Helper.mergeObjects({}, obj1, obj2), obj3, "Three objects merged properly"); + }); + + + assert.test("Keyboard event helper", function(assert) { + assert.plan(2); + + document.addEventListener("keydown", function(event) { + assert.equal(Helper.getKey(event), keyCode, "Event keyCode obtained"); + assert.ok(Helper.getKeyModifier(event, keyModifier), "Event keyModifier obtained"); + }); + + document.documentElement.dispatchEvent(kbdEvent); + }); + + +});
dotjay/hashgrid
af1f999bdf5b59775761ffc4cf27766c586e5ef7
Create Storage module
diff --git a/src/storage.js b/src/storage.js new file mode 100644 index 0000000..f78ab8c --- /dev/null +++ b/src/storage.js @@ -0,0 +1,35 @@ +/* + * This is just a proxy for storage function + * Ideally, local storage is used, + * cookie storage is provided only as fallback +*/ + +if (typeof module!='undefined' && module.exports) { + var LocalStorage = require("./localStorage"); + var CookieStorage = require("./cookieStorage"); +} + +var Storage = function() { + if(this.hasLocalStorage()) { + return new LocalStorage(); + } + else { + return new CookieStorage(); + } +}; + +Storage.prototype.hasLocalStorage = function() { + try { + var storage = window.localStorage, + someData = "some value"; + + storage.setItem(someData, someData); + storage.removeItem(someData); + return true; + } + catch(e) { + return false; + } +}; + +if (typeof module!="undefined" && module.exports) module.exports = Storage;
dotjay/hashgrid
6b4428bf823e7b8f8382356d1aa8996a2c2d70ee
Create Local Storage module
diff --git a/src/localStorage.js b/src/localStorage.js new file mode 100644 index 0000000..0a716ce --- /dev/null +++ b/src/localStorage.js @@ -0,0 +1,39 @@ +var LocalStorage = (function() { + + function LocalStorage() { + this.storage = window.localStorage; + } + + LocalStorage.prototype.read = function(dataLabel) { + var dataValue = this.storage.getItem(dataLabel); + + if(dataValue) { + return JSON.parse(dataValue); + } + else { + return null; + } + }; + + LocalStorage.prototype.write = function(dataLabel, dataValue) { + this.storage.setItem(dataLabel, JSON.stringify(dataValue)); + return dataValue; + }; + + LocalStorage.prototype.remove = function(dataLabel) { + var removedDataValue = this.read(dataLabel); + + if(removedDataValue) { + this.storage.removeItem(dataLabel); + return removedDataValue; + } + else { + return null; + } + }; + + return LocalStorage; + +})(); + +if (typeof module!="undefined" && module.exports) module.exports = LocalStorage; diff --git a/tests/localStorage.js b/tests/localStorage.js new file mode 100644 index 0000000..f555b20 --- /dev/null +++ b/tests/localStorage.js @@ -0,0 +1,22 @@ +var tape = require("tape"); +var LocalStorage = require("../src/localStorage"); + +tape("Local Storage module", function(assert) { + var storage = new LocalStorage(); + var dataLabel = "label"; + var dataValue = "value"; + + window.localStorage.clear(); + + assert.equal(storage.read(dataLabel), null, "Data reading returns null if data value is not set"); + + assert.ok(storage.write(dataLabel, dataValue), "Data writing returns written value"); + + assert.equal(storage.read(dataLabel), dataValue, "Data writing sets valid data value"); + + assert.equal(storage.remove(dataLabel), dataValue, "Data removal returns removed value"); + + assert.equal(storage.read(dataLabel), null, "Data reading returns null after data value is removed"); + + assert.end(); +});
dotjay/hashgrid
36c058abaebec505dd1669add35bc33417f591c3
Create Cookie Storage module
diff --git a/src/cookieStorage.js b/src/cookieStorage.js new file mode 100644 index 0000000..68cf2f4 --- /dev/null +++ b/src/cookieStorage.js @@ -0,0 +1,74 @@ +/** + * Based on cookie functions + * By Peter-Paul Koch: + * http://www.quirksmode.org/js/cookies.html +*/ + +var CookieStorage = (function() { + + function CookieStorage() { + + } + + CookieStorage.prototype.read = function(cookieLabel) { + + var + cookieCrumb, + cookieArray = document.cookie.split(";"), + i = 0, + cookieCrumbCount = cookieArray.length; + + cookieLabel = cookieLabel + "="; + + for(; i < cookieCrumbCount; i++) { + cookieCrumb = cookieArray[i]; + + while(cookieCrumb.charAt(0) === " ") { + cookieCrumb = cookieCrumb.substring(1, cookieCrumb.length); + } + + if(cookieCrumb.indexOf(cookieLabel) === 0) { + return JSON.parse(cookieCrumb.substring(cookieLabel.length, cookieCrumb.length)); + } + } + + return null; + }; + + CookieStorage.prototype.write = function(cookieLabel, cookieValue, expirationDay) { + + var + date, + cookieExpires = "", + toBeWritten = ""; + + if (expirationDay) { + date = new Date(); + date.setTime( date.getTime() + (expirationDay*24*60*60*1000) ); + cookieExpires = "; expires=" + date.toGMTString(); + } + + toBeWritten = cookieLabel + "=" + JSON.stringify(cookieValue) + cookieExpires + "; path=/"; + document.cookie = toBeWritten; + + return toBeWritten; + }; + + CookieStorage.prototype.remove = function(cookieLabel) { + var removedCookieValue = this.read(cookieLabel); + + if(removedCookieValue) { + this.write(cookieLabel, "", -1); + return removedCookieValue; + } + else { + return null; + } + }; + + return CookieStorage; + +})(); + + +if (typeof module!="undefined" && module.exports) module.exports = CookieStorage; diff --git a/tests/cookieStorage.js b/tests/cookieStorage.js new file mode 100644 index 0000000..0765591 --- /dev/null +++ b/tests/cookieStorage.js @@ -0,0 +1,20 @@ +var tape = require("tape"); +var CookieStorage = require("../src/cookieStorage"); + +tape("Cookie Storage module", function(assert) { + var storage = new CookieStorage(); + var cookieLabel = "label"; + var cookieValue = "value"; + + assert.equal(storage.read(cookieLabel), null, "Cookie reading returns null if cookie value is not set"); + + assert.ok(storage.write(cookieLabel, cookieValue), "Cookie writing returns written value"); + + assert.equal(storage.read(cookieLabel), cookieValue, "Cookie writing sets valid cookie value"); + + assert.equal(storage.remove(cookieLabel), cookieValue, "Cookie removal returns removed value"); + + assert.equal(storage.read(cookieLabel), null, "Cookie reading returns null after cookie value is removed"); + + assert.end(); +});
dotjay/hashgrid
20a62115bf1e537850c51392e5765ff65c17268d
Add test command
diff --git a/package.json b/package.json index d7db2a2..2959e42 100644 --- a/package.json +++ b/package.json @@ -1,29 +1,29 @@ { "name": "hashgrid", "version": "9.0.0", "description": "A little tool that inserts a layout grid in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background.", "main": "hashgrid.js", "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" + "test": "./node_modules/.bin/hihat tests/*.js -p tap-dev-tool" }, "repository": { "type": "git", "url": "git+https://github.com/widatama/hashgrid.git" }, "author": "", "license": "Apache-2.0", "bugs": { "url": "https://github.com/widatama/hashgrid/issues" }, "homepage": "https://github.com/widatama/hashgrid#readme", "devDependencies": { "grunt": "^0.4.5", "grunt-contrib-clean": "^0.7.0", "grunt-contrib-uglify": "^0.11.0", "grunt-contrib-watch": "^0.6.1", "hihat": "^2.5.0", "load-grunt-config": "^0.19.0", "tap-dev-tool": "^1.3.0", "tape": "^4.2.2" } }
dotjay/hashgrid
27fce880d7f92ac38a50299ac4f26516a40b125f
Install dev dependencies
diff --git a/package.json b/package.json index ca10b32..d7db2a2 100644 --- a/package.json +++ b/package.json @@ -1,19 +1,29 @@ { "name": "hashgrid", "version": "9.0.0", "description": "A little tool that inserts a layout grid in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background.", "main": "hashgrid.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/widatama/hashgrid.git" }, "author": "", "license": "Apache-2.0", "bugs": { "url": "https://github.com/widatama/hashgrid/issues" }, - "homepage": "https://github.com/widatama/hashgrid#readme" + "homepage": "https://github.com/widatama/hashgrid#readme", + "devDependencies": { + "grunt": "^0.4.5", + "grunt-contrib-clean": "^0.7.0", + "grunt-contrib-uglify": "^0.11.0", + "grunt-contrib-watch": "^0.6.1", + "hihat": "^2.5.0", + "load-grunt-config": "^0.19.0", + "tap-dev-tool": "^1.3.0", + "tape": "^4.2.2" + } }
dotjay/hashgrid
49ad4b4c927e7d5e125f5f86c6a9e85b21952bb3
Add gitignore
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d733f17 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +.DS_Store + +node_modules/ + +temp*/ +tmp/ +*.log
dotjay/hashgrid
333f8c425c60a8f623e846aa86a8db64675d65c4
Turn into npm project
diff --git a/package.json b/package.json new file mode 100644 index 0000000..ca10b32 --- /dev/null +++ b/package.json @@ -0,0 +1,19 @@ +{ + "name": "hashgrid", + "version": "9.0.0", + "description": "A little tool that inserts a layout grid in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background.", + "main": "hashgrid.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/widatama/hashgrid.git" + }, + "author": "", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/widatama/hashgrid/issues" + }, + "homepage": "https://github.com/widatama/hashgrid#readme" +}
dotjay/hashgrid
3c1fd39c487ec5294991dc7e4a0c097f7b09dc23
Fix install info in README again
diff --git a/README.md b/README.md index 2c9310a..a5470f3 100644 --- a/README.md +++ b/README.md @@ -1,53 +1,46 @@ # #grid # A little tool that inserts a layout grid in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. ## Features ## * Adaptable for all layout widths and alignments * Adaptable for any vertical rhythm value * Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids * Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters ## Install ## Download the latest release from: + https://github.com/dotjay/hashgrid/releases Install using [Bower](http://bower.io/): ``` bower install hashgrid#v9 ``` Notes on usage can be found at [hashgrid.com#installation](http://hashgrid.com/#installation). -## Install ## - -Download the latest release from: -https://github.com/dotjay/hashgrid/releases - -Install using [Bower](http://bower.io/): -```bower install hashgrid#v9``` - ## License ## Copyright 2013 Analog Coop Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -- This essentially means that you're free to copy, modify and distribute it for any project so long as you provide clear attribution to Analog Coop Limited. Contact us if you need a different license. http://analog.coop/
dotjay/hashgrid
9be8d59ad3c2e36f001f39424be9250ebb8d82a9
Fixing install info in README
diff --git a/README.md b/README.md index f98a5cb..263445b 100644 --- a/README.md +++ b/README.md @@ -1,43 +1,45 @@ # #grid # A little tool that inserts a layout grid in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. ## Features ## * Adaptable for all layout widths and alignments * Adaptable for any vertical rhythm value * Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids * Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters ## Install ## Download the latest release from: https://github.com/dotjay/hashgrid/releases Install using [Bower](http://bower.io/): -```bower install hashgrid#v9``` +``` +bower install hashgrid#v9 +``` Notes on usage can be found at [hashgrid.com#installation](http://hashgrid.com/#installation). ## License ## Copyright 2013 Analog Coop Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -- This essentially means that you're free to copy, modify and distribute it for any project so long as you provide clear attribution to Analog Coop Limited. Contact us if you need a different license. http://analog.coop/
dotjay/hashgrid
149412e64c4469f16fa48dfc85ce06a5d4fef2a0
Adding install info to README
diff --git a/README.md b/README.md index 7579758..f98a5cb 100644 --- a/README.md +++ b/README.md @@ -1,35 +1,43 @@ # #grid # A little tool that inserts a layout grid in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. ## Features ## * Adaptable for all layout widths and alignments * Adaptable for any vertical rhythm value * Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids * Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters -Notes on installation and usage can be found in the included index.htm file. +## Install ## + +Download the latest release from: +https://github.com/dotjay/hashgrid/releases + +Install using [Bower](http://bower.io/): +```bower install hashgrid#v9``` + +Notes on usage can be found at [hashgrid.com#installation](http://hashgrid.com/#installation). ## License ## Copyright 2013 Analog Coop Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -- This essentially means that you're free to copy, modify and distribute it for any project so long as you provide clear attribution to Analog Coop Limited. Contact us if you need a different license. http://analog.coop/
dotjay/hashgrid
3213ee1bc477e90ced9cbb55b045922c97d2f31c
Adding install info to README
diff --git a/README.md b/README.md index 7579758..09921c0 100644 --- a/README.md +++ b/README.md @@ -1,35 +1,43 @@ # #grid # A little tool that inserts a layout grid in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. ## Features ## * Adaptable for all layout widths and alignments * Adaptable for any vertical rhythm value * Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids * Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters Notes on installation and usage can be found in the included index.htm file. +## Install ## + +Download the latest release from: +https://github.com/dotjay/hashgrid/releases + +Install using [Bower](http://bower.io/): +```bower install hashgrid#v9``` + ## License ## Copyright 2013 Analog Coop Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -- This essentially means that you're free to copy, modify and distribute it for any project so long as you provide clear attribution to Analog Coop Limited. Contact us if you need a different license. http://analog.coop/
dotjay/hashgrid
7fc6eaccbaac2b2b478fdea56eb31ae81c874544
Seems bower version number needs to match a target commit tag (currently v9)
diff --git a/bower.json b/bower.json index 7c40479..2babd4a 100644 --- a/bower.json +++ b/bower.json @@ -1,9 +1,9 @@ { "name": "hashgrid", - "version": "9.0", + "version": "v9", "main": "hashgrid.js", "description": "A little tool that inserts a layout grid in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background.", "ignore": [ "index.htm" ] }
dotjay/hashgrid
ed847abca11f63ef9fb36dbc097486d179f62216
Tweak bower version number to fit with semver.org requirements
diff --git a/bower.json b/bower.json index 4946b66..7c40479 100644 --- a/bower.json +++ b/bower.json @@ -1,9 +1,9 @@ { "name": "hashgrid", - "version": "9", + "version": "9.0", "main": "hashgrid.js", "description": "A little tool that inserts a layout grid in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background.", "ignore": [ "index.htm" ] }
dotjay/hashgrid
d37595b5731cab87910c818b129dc9f81cb5ed1c
Add bower.json
diff --git a/bower.json b/bower.json new file mode 100644 index 0000000..4946b66 --- /dev/null +++ b/bower.json @@ -0,0 +1,9 @@ +{ + "name": "hashgrid", + "version": "9", + "main": "hashgrid.js", + "description": "A little tool that inserts a layout grid in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background.", + "ignore": [ + "index.htm" + ] +}
dotjay/hashgrid
c0819a8b49e663ea06457a5241fd9cb0f34ee558
Moving the example instantiation of hashgrid() out of the script itself to avoid potential conflicts (re Issue #17). Increase to v9 for next release.
diff --git a/hashgrid.js b/hashgrid.js index 193ddbc..cb72466 100644 --- a/hashgrid.js +++ b/hashgrid.js @@ -1,435 +1,422 @@ /** * hashgrid (jQuery version, adapters are on the way) * http://github.com/dotjay/hashgrid - * Version 8, 06 Oct 2012 + * Version 9, 30 May 2013 * Written by Jon Gibbins * * Contibutors: * James Aitken, http://loonypandora.co.uk/ * Tom Arnold, http://www.tomarnold.de/ * Sean Coates, http://seancoates.com/ * Phil Dokas, http://jetless.org/ * Andrew Jaswa, http://andrewjaswa.com/ * Callum Macrae, http://lynx.io/ */ /** * @license Copyright 2012 Analog Coop Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Usage * * // The basic #grid setup looks like this * var grid = new hashgrid(); * * // But there are a whole bunch of additional options you can set * var grid = new hashgrid({ * id: 'mygrid', // set a custom id for the grid container * modifierKey: 'alt', // optional 'ctrl', 'alt' or 'shift' * showGridKey: 's', // key to show the grid * holdGridKey: 'enter', // key to hold the grid in place * foregroundKey: 'f', // key to toggle foreground/background * jumpGridsKey: 'd', // key to cycle through the grid classes * numberOfGrids: 2, // number of grid classes used * classPrefix: 'myclass', // prefix for the grid classes * cookiePrefix: 'mygrid' // prefix for the cookie name * }); */ /** * Make sure we have the library * TODO: Use an adapter */ if (typeof jQuery == "undefined") { alert("Hashgrid: jQuery not loaded. Make sure it's linked to your pages."); } /** * hashgrid overlay * @constructor */ var hashgrid = function(set) { var options = { id: 'grid', // id for the grid container modifierKey: null, // optional 'ctrl', 'alt' or 'shift' showGridKey: 'g', // key to show the grid holdGridKey: 'h', // key to hold the grid in place foregroundKey: 'f', // key to toggle foreground/background jumpGridsKey: 'j', // key to cycle through the grid classes numberOfGrids: 1, // number of grid classes used classPrefix: 'grid-', // prefix for the grid classes cookiePrefix: 'hashgrid'// prefix for the cookie name }, alreadyDown, classNumber = 1, gridLines, gridWidth, i, line, lineHeight, numGridLines, overlay, overlayCookie, overlayEl, overlayOn = false, overlayVert, overlayZState = 'B', overlayZBackground = -1, overlayZForeground = 9999, pageHeight, setKey, state, sticky = false, top; // Apply options if (typeof set == 'object') { for (setKey in set) { options[setKey] = set[setKey]; } } else if (typeof set == 'string') { options.id = set; } // Remove any conflicting overlay if ($('#' + options.id).length > 0) { $('#' + options.id).remove(); } // Create overlay, hidden before adding to DOM overlayEl = $('<div></div>'); overlayEl .attr('id', options.id) .css({ display: 'none', pointerEvents: 'none' }); $("body").prepend(overlayEl); overlay = $('#' + options.id); // Unless a custom z-index is set, ensure the overlay will be behind everything if (overlay.css('z-index') == 'auto') overlay.css('z-index', overlayZBackground); // Override the default overlay height with the actual page height pageHeight = parseFloat($(document).height()); overlay.height(pageHeight); // Add the first grid line so that we can measure it overlay.append('<div id="' + options.id + '-horiz" class="horiz first-line">'); // Position off-screen and display to calculate height top = overlay.css("top"); overlay.css({ top: '-999px', display: 'block' }); // Calculate the number of grid lines needed line = $('#' + options.id + '-horiz'); lineHeight = line.outerHeight(); // Hide and reset top overlay.css({ display: 'none', top: top }); // Break on zero line height if (lineHeight <= 0) { return false; } // Add the remaining grid lines numGridLines = Math.floor(pageHeight / lineHeight); gridLines = ''; for (i = numGridLines - 1; i >= 1; i--) { gridLines += '<div class="horiz"></div>'; } overlay.append(gridLines); // vertical grid overlay.append($('<div class="vert-container"></div>')); overlayVert = overlay.children('.vert-container'); gridWidth = overlay.width(); overlayVert.css({width: gridWidth, position: 'absolute', top: 0}); overlayVert.append('<div class="vert first-line">&nbsp;</div>'); // 30 is an arbitrarily large number... // can't calculate the margin width properly gridLines = ''; for (i = 0; i < 30; i++) { gridLines += '<div class="vert">&nbsp;</div>'; } overlayVert.append(gridLines); overlayVert.children() .height(pageHeight) .css({ display: 'inline-block' }); // Check for saved state overlayCookie = readCookie(options.cookiePrefix + options.id); if (typeof overlayCookie == 'string') { state = overlayCookie.split('-'); state[2] = Number(state[2]); if ((typeof state[2] == 'number') && !isNaN(state[2])) { classNumber = state[2].toFixed(0); overlay.addClass(options.classPrefix + classNumber); } if (state[1] == 'F') { overlayZState = 'F'; overlay.css('z-index', overlayZForeground); } if (state[0] == '1') { overlayOn = true; sticky = true; showOverlay(); } } else { overlay.addClass(options.classPrefix + classNumber); } // Keyboard controls $(document).bind('keydown', keydownHandler); $(document).bind('keyup', keyupHandler); /** * Helpers */ function getModifier(e) { if (options.modifierKey == null) return true; // Bypass by default var m = true; switch(options.modifierKey) { case 'ctrl': m = (e.ctrlKey ? e.ctrlKey : false); break; case 'alt': m = (e.altKey ? e.altKey : false); break; case 'shift': m = (e.shiftKey ? e.shiftKey : false); break; } return m; } function getKey(e) { var k = false, c = (e.keyCode ? e.keyCode : e.which); // Handle keywords if (c == 13) k = 'enter'; // Handle letters else k = String.fromCharCode(c).toLowerCase(); return k; } function saveState() { createCookie(options.cookiePrefix + options.id, (sticky ? '1' : '0') + '-' + overlayZState + '-' + classNumber, 1); } function showOverlay() { overlay.show(); overlayVert.css({width: overlay.width()}); // hide any vertical blocks that aren't at the top of the viewport overlayVert.children('.vert').each(function () { var vCol = $(this); vCol.css('display','inline-block'); if (vCol.offset().top > vCol.parent().offset().top) { vCol.hide(); } }); } /** * Event handlers */ alreadyDown = {}; function keydownHandler(e) { var k, m, source = e.target.tagName.toLowerCase(); if ((source == 'input') || (source == 'textarea') || (source == 'select')) { return true; } m = getModifier(e); if (!m) { return true; } k = getKey(e); if (!k) { return true; } if (alreadyDown[k]) { return true; } alreadyDown[k] = true; switch(k) { case options.showGridKey: if (!overlayOn) { showOverlay(); overlayOn = true; } else if (sticky) { overlay.hide(); overlayOn = false; sticky = false; saveState(); } break; case options.holdGridKey: if (overlayOn && !sticky) { // Turn sticky overlay on sticky = true; saveState(); } break; case options.foregroundKey: if (overlayOn) { // Toggle sticky overlay z-index if (overlay.css('z-index') == overlayZForeground) { overlay.css('z-index', overlayZBackground); overlayZState = 'B'; } else { overlay.css('z-index', overlayZForeground); overlayZState = 'F'; } saveState(); } break; case options.jumpGridsKey: if (overlayOn && (options.numberOfGrids > 1)) { // Cycle through the available grids overlay.removeClass(options.classPrefix + classNumber); classNumber++; if (classNumber > options.numberOfGrids) classNumber = 1; overlay.addClass(options.classPrefix + classNumber); showOverlay(); if (/webkit/.test( navigator.userAgent.toLowerCase() )) { forceRepaint(); } saveState(); } break; } return true; } function keyupHandler(e) { var k, m = getModifier(e); if (!m) { return true; } k = getKey(e); alreadyDown[k] = false; if (k && (k == options.showGridKey) && !sticky) { overlay.hide(); overlayOn = false; } return true; } /** * Cookie functions * * By Peter-Paul Koch: * http://www.quirksmode.org/js/cookies.html */ function createCookie(name, value, days) { var date, expires = ""; if (days) { date = new Date(); date.setTime( date.getTime() + (days*24*60*60*1000) ); expires = "; expires=" + date.toGMTString(); } document.cookie = name + "=" + value + expires + "; path=/"; } function readCookie(name) { var c, ca = document.cookie.split(';'), i = 0, len = ca.length, nameEQ = name + "="; for (; i < len; i++) { c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1, c.length); } if (c.indexOf(nameEQ) == 0) { return c.substring(nameEQ.length, c.length); } } return null; } function eraseCookie(name) { createCookie(name, "", -1); } /** * Forces a repaint (because WebKit has issues) * http://www.sitepoint.com/forums/showthread.php?p=4538763 * http://www.phpied.com/the-new-game-show-will-it-reflow/ */ function forceRepaint() { var ss = document.styleSheets[0]; try { ss.addRule('.xxxxxx', 'position: relative'); ss.removeRule(ss.rules.length - 1); } catch(e) {} } return {}; }; - - -/** - * You can call hashgrid from your own code, but it's loaded here as - * an example for your convenience. - */ -$(document).ready(function() { - - var grid = new hashgrid({ - numberOfGrids: 2 - }); - -}); diff --git a/index.htm b/index.htm index 96d0d9d..6a2f75c 100644 --- a/index.htm +++ b/index.htm @@ -1,461 +1,473 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>#grid</title> <style type="text/css"> /* Putting inline rules here so the document can be downloaded with style */ body{ font-size: 1em; line-height: 1.25; font-family: Arial, sans-serif; background: White; color: DimGray; margin: 0; padding: 0 20px; } #content{ font-size: 16px; line-height: 20px; position: relative; } #content{ width: 620px; margin: 0 auto; } #footer{ border-top: 1px dotted DarkGray; padding-top: 19px; } h1, h2{ color: Black; font-weight: normal; } h1{ font-size: 36px; line-height: 40px; margin: 40px 0 20px; padding-bottom: 19px; border-bottom: 1px dotted DarkGray; } h1 em{ font-style: normal; color: DarkGray; font-size: 16px; line-height: 20px; margin: 0 0 20px; } h2, h3{ font-size: 16px; font-weight: 700; line-height: 20px; margin: 0 0 20px; } h3{ font-weight: 300; } a:link, a:visited{ color: Black; text-decoration: none; padding: 0 2px; background-color: WhiteSmoke; border-bottom: 1px solid Gold; } a:focus{ outline: none; } a:focus, a:hover, a:active{ background-color: Khaki; border-bottom: 1px solid GoldenRod; } p, ul{ padding: 0; margin: 0 0 20px; } dl, ol{ padding: 0; margin: 0; } ul{ list-style: circle; } ol li{ margin-bottom: 20px; } dd{ margin: 0 0 20px 0; } del{ text-decoration: line-through; opacity: 0.75; } ins{ text-decoration: none; } code{ font-size: 14px; line-height: 1; } textarea{ font-family: 'Courier New', monospace; font-size: 14px; line-height: 20px; display: block; width: 600px; margin: 0 0 20px; padding: 0 0 0 15px; border: 0; color: Black; background: Gainsboro; border-left: 5px solid DarkGray; } #javascript-code{ -height: 180px; +height: 280px; } #css-code{ height: 1300px; } .summary em{ font-style: normal; position: absolute; color: DarkGray; right: 0; top: 18px; width: 140px; } .summary em span{ position: absolute; left: -9999px; } #download{ line-height: 60px; padding: 0 40px 0 15px; border-left: 5px solid DarkGray; background: Gainsboro; color: DimGray; } span.key{ color: Black; text-transform: uppercase; } </style> <!-- Set styles --> <style type="text/css"> /** * Grid */ #grid{ /* Dimensions - same width as your grid with gutters */ width: 980px; /* Grid (left-aligned) position: absolute; top: 0; left: 0; */ /* Grid (centered) */ position: absolute; top: 0; left: 50%; margin-left: -490px; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ #grid div.vert{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-right: 19px; } #grid div.vert.first-line{ margin-left: 19px; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ #grid div.horiz{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option in the hashgrid.js file. */ #grid.grid-1 div.vert{ /* Vertical grid line colour for grid 1 */ border-color: darkturquoise; } #grid.grid-2{ /* Adjustments */ padding: 0 160px; width: 660px; } #grid.grid-2 div.vert{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </style> </head> <body> <div id="content" role="main"> -<h1>#grid <em>v8</em></h1> +<h1>#grid <em>v9</em></h1> <p class="summary"><em>Sat, 6 Oct 2012<span>:</span></em> This is a little tool we created for our <a href="http://analog.coop/">Analog&#160;holding&#160;page</a>. It inserts a <a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a> in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit <span class="key">G</span> on your keyboard.</p> <h2>Download</h2> <p id="download"><a href="https://github.com/dotjay/hashgrid/downloads">Download #grid</a> from <a href="https://github.com/dotjay/hashgrid">GitHub</a></p> <h2 id="features">Features</h2> <ul> <li>Adaptable for all layout widths and alignments</li> <li>Adaptable for any vertical rhythm value</li> <li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li> <li>Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters</li> </ul> <p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p> <h2 id="installation">Installation</h2> <ol> -<li><h3>Copy the <a href="https://github.com/dotjay/hashgrid/blob/v8/hashgrid.js">hashgrid.js</a> script to your project</h3></li> +<li><h3>Copy the <a href="https://github.com/dotjay/hashgrid/blob/v9/hashgrid.js">hashgrid.js</a> script to your project</h3></li> <li><h3>Add the script to your page(s) just inside the <code>&#60;/body&#62;</code> tag</h3> -<textarea id="javascript-code" cols="68" rows="8" readonly="readonly"> +<textarea id="javascript-code" cols="68" rows="14" readonly="readonly"> &#60;!-- Grab latest version of jQuery --&#62; &#60;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"&#62; &#60;/script&#62; &#60;!-- Include the hashgrid script --&#62; -&#60;script type="text/javascript" src="hashgrid.js"&#62;&#60;/script&#62;</textarea></li> +&#60;script type="text/javascript" src="hashgrid.js"&#62;&#60;/script&#62; + +&#60;!-- Kick hashgrid into action --&#62; +&#60;script type="text/javascript"&#62; +var grid = new hashgrid({ numberOfGrids: 2 }); +&#60;/script&#62;</textarea></li> <li><h3>Add the CSS to your page(s)</h3> <textarea id="css-code" cols="68" rows="64" readonly="readonly"> /** * Grid */ #grid{ /* Dimensions - same width as your grid with gutters */ width: 980px; /* Grid (left-aligned) position: absolute; top: 0; left: 0; */ /* Grid (centered) */ position: absolute; top: 0; left: 50%; margin-left: -490px; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ #grid div.vert{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-right: 19px; } #grid div.vert.first-line{ margin-left: 19px; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ #grid div.horiz{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option in the hashgrid.js file. */ #grid.grid-1 div.vert{ /* Vertical grid line colour for grid 1 */ border-color: darkturquoise; } #grid.grid-2{ /* Adjustments */ padding: 0 160px; width: 660px; } #grid.grid-2 div.vert{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </textarea></li> <li><h3>Modify #grid to suit your needs</h3> <p>The CSS and JavaScript is annotated to help you.</p></li> </ol> <h2 id="usage">Usage</h2> <p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p> <dl> <dt><span class="key">G</span></dt> <dd>Show the grid until you release.</dd> <dt><span class="key">G</span> + <span class="key">H</span></dt> <dd>Show and hold the grid (<span class="key">G</span> will remove it again).</dd> <dt><span class="key">G</span> + <span class="key">F</span></dt> <dd>Toggle the grid to the foreground and back. Pressing <span class="key">F</span> while the grid is held also works.</dd> <dt><span class="key">G</span> + <span class="key">J</span></dt> <dd>Jump to the next grid. Pressing <span class="key">J</span> while the grid is held also works.</dd> </dl> <p><em>N.B. A cookie conveniently remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page except in Chrome v4, Safari v4, Firefox v3.6, or more recent versions.</em></p> <h2 id="release-notes">Release Notes</h2> <dl> +<dt>v9&#8201;&#8212;&#8201;30 May 2013</dt> +<dd>Minor release: Improved example usage to avoid conflicts.</dd> <dt>v8&#8201;&#8212;&#8201;6 Oct 2012</dt> <dd> <ul> <li>Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="http://www.tomarnold.de/">Tom Arnold</a>.</li> <li>Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="http://lynx.io/">Callum Macrae</a>.</li> <li>Fixes to cookie handling. Thanks to <a href="http://loonypandora.co.uk/">James Aitken</a>.</li> <li>Optimisations.</li> </ul> </dd> <dt>v7&#8201;&#8212;&#8201;11 Jun 2011</dt> <dd>Minor release: Updated license references.</dd> <dt>v6&#8201;&#8212;&#8201;10 Jun 2011</dt> <dd>Minor release: Optimisations (thanks to <a href="http://andrewjaswa.com/">Andrew Jaswa</a> for contributions), and now released under an Apache License.</dd> <dt>v5&#8201;&#8212;&#8201;3 Nov 2010</dt> <dd> <ul> <li>Vertical grid lines can now be set using CSS&#8230; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution.</li> <li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li> <li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback.</li> </ul> </dd> <dt>v4&#8201;&#8212;&#8201;29 Mar 2010</dt> <dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd> <dt>v3&#8201;&#8212;&#8201;22 Feb 2010</dt> <dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd> <dt>v2&#8201;&#8212;&#8201;2 Feb 2010</dt> <dd> <ul> <li>Keys are now more easily configured (see top of hashgrid.js).</li> <li>Fixed crash when using with disabled CSS.</li> <li>Renamed the GridOverlay object to hashgrid.</li> </ul> </dd> <dt>v1&#8201;&#8212;&#8201;21 Dec 2009</dt> <dd>First release.</dd> </dl> <h2 id="known-issues">Known Issues</h2> <ul> <li><del>IE 8: Fully functional, but the default <span class="key">ALT</span> + <span class="key">G</span> + <span class="key">ENTER</span> shortcut puts IE into full screen mode. Hit <span class="key">ALT</span> + <span class="key">ENTER</span> to toggle full screen mode off again.</del><ins datetime="2010-02-22"> The default keyboard shortcuts have been changed.</ins></li> <li>IE 6: The grid is always in the foreground.</li> <li>Opera 9/10: Using <span class="key">CTRL</span> or <span class="key">ALT</span> as a modifier key will not work due to different key handling by the browser.</li> </ul> <h2 id="license">License</h2> <p>Copyright 2012 Analog Coop Limited</p> <p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br /><br /> <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a></p> <p>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.</p> <p>This essentially means that you&#8217;re free to copy, modify and distribute it for any project so long as you provide clear attribution to Analog Coop Limited. <a href="http://analog.coop/#talk-to-us">Contact us</a> if you need a different license.</p> <div id="footer" role="contentinfo"> <p>#grid is an <a href="http://analog.coop/">Analog</a> gig. It was conceived by <a href="http://jontangerine.com/">Jon Tan</a>, and built by <a href="http://accessibility.co.uk/">Jon Gibbins</a>, in cahoots with our <a href="http://analog.coop#is">fine friends</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p> </div> </div> <!-- Grab latest version of jQuery --> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script> <!-- Include the hashgrid script --> <script type="text/javascript" src="hashgrid.js"></script> +<!-- Kick hashgrid into action --> +<script type="text/javascript"> +var grid = new hashgrid({ numberOfGrids: 2 }); +</script> + </body> </html>
dotjay/hashgrid
d0b09c981f5b8b307bbf4cb2b900cc49bb67db70
safer comparison with null
diff --git a/hashgrid.js b/hashgrid.js index 8167b6d..0a0ae62 100644 --- a/hashgrid.js +++ b/hashgrid.js @@ -1,436 +1,436 @@ /** * hashgrid (jQuery version, adapters are on the way) * http://github.com/dotjay/hashgrid * Version 8, 06 Oct 2012 * Written by Jon Gibbins * * Contibutors: * James Aitken, http://loonypandora.co.uk/ * Tom Arnold, http://www.tomarnold.de/ * Sean Coates, http://seancoates.com/ * Phil Dokas, http://jetless.org/ * Andrew Jaswa, http://andrewjaswa.com/ * Callum Macrae, http://lynx.io/ */ /** * @license Copyright 2011 Analog Coop Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Usage * * // The basic #grid setup looks like this * var grid = new hashgrid(); * * // But there are a whole bunch of additional options you can set * var grid = new hashgrid({ * id: 'mygrid', // set a custom id for the grid container * modifierKey: 'alt', // optional 'ctrl', 'alt' or 'shift' * showGridKey: 's', // key to show the grid * holdGridKey: 'enter', // key to hold the grid in place * foregroundKey: 'f', // key to toggle foreground/background * jumpGridsKey: 'd', // key to cycle through the grid classes * numberOfGrids: 2, // number of grid classes used * classPrefix: 'myclass', // prefix for the grid classes * cookiePrefix: 'mygrid' // prefix for the cookie name * }); */ /** * Make sure we have the library * TODO: Use an adapter */ if (typeof jQuery == "undefined") { alert("Hashgrid: jQuery not loaded. Make sure it's linked to your pages."); } /** * hashgrid overlay * @constructor */ var hashgrid = function(set) { var $ = jQuery; var options = { id: 'grid', // id for the grid container modifierKey: null, // optional 'ctrl', 'alt' or 'shift' showGridKey: 'g', // key to show the grid holdGridKey: 'h', // key to hold the grid in place foregroundKey: 'f', // key to toggle foreground/background jumpGridsKey: 'j', // key to cycle through the grid classes numberOfGrids: 1, // number of grid classes used classPrefix: 'grid-', // prefix for the grid classes cookiePrefix: 'hashgrid'// prefix for the cookie name }, alreadyDown, classNumber = 1, gridLines, gridWidth, i, line, lineHeight, numGridLines, overlay, overlayCookie, overlayEl, overlayOn = false, overlayVert, overlayZState = 'B', overlayZBackground = -1, overlayZForeground = 9999, pageHeight, setKey, state, sticky = false, top; // Apply options if (typeof set == 'object') { for (setKey in set) { options[setKey] = set[setKey]; } } else if (typeof set == 'string') { options.id = set; } // Remove any conflicting overlay if ($('#' + options.id).length > 0) { $('#' + options.id).remove(); } // Create overlay, hidden before adding to DOM overlayEl = $('<div></div>'); overlayEl .attr('id', options.id) .css({ display: 'none', pointerEvents: 'none' }); $("body").prepend(overlayEl); overlay = $('#' + options.id); // Unless a custom z-index is set, ensure the overlay will be behind everything if (overlay.css('z-index') == 'auto') overlay.css('z-index', overlayZBackground); // Override the default overlay height with the actual page height pageHeight = parseFloat($(document).height()); overlay.height(pageHeight); // Add the first grid line so that we can measure it overlay.append('<div id="' + options.id + '-horiz" class="horiz first-line">'); // Position off-screen and display to calculate height top = overlay.css("top"); overlay.css({ top: '-999px', display: 'block' }); // Calculate the number of grid lines needed line = $('#' + options.id + '-horiz'); lineHeight = line.outerHeight(); // Hide and reset top overlay.css({ display: 'none', top: top }); // Break on zero line height if (lineHeight <= 0) { return false; } // Add the remaining grid lines numGridLines = Math.floor(pageHeight / lineHeight); gridLines = ''; for (i = numGridLines - 1; i >= 1; i--) { gridLines += '<div class="horiz"></div>'; } overlay.append(gridLines); // vertical grid overlay.append($('<div class="vert-container"></div>')); overlayVert = overlay.children('.vert-container'); gridWidth = overlay.width(); overlayVert.css({width: gridWidth, position: 'absolute', top: 0}); overlayVert.append('<div class="vert first-line">&nbsp;</div>'); // 30 is an arbitrarily large number... // can't calculate the margin width properly gridLines = ''; for (i = 0; i < 30; i++) { gridLines += '<div class="vert">&nbsp;</div>'; } overlayVert.append(gridLines); overlayVert.children() .height(pageHeight) .css({ display: 'inline-block' }); // Check for saved state overlayCookie = readCookie(options.cookiePrefix + options.id); if (typeof overlayCookie == 'string') { state = overlayCookie.split('-'); state[2] = Number(state[2]); if ((typeof state[2] == 'number') && !isNaN(state[2])) { classNumber = state[2].toFixed(0); overlay.addClass(options.classPrefix + classNumber); } if (state[1] == 'F') { overlayZState = 'F'; overlay.css('z-index', overlayZForeground); } if (state[0] == '1') { overlayOn = true; sticky = true; showOverlay(); } } else { overlay.addClass(options.classPrefix + classNumber); } // Keyboard controls $(document).bind('keydown', keydownHandler); $(document).bind('keyup', keyupHandler); /** * Helpers */ function getModifier(e) { - if (options.modifierKey == null) return true; // Bypass by default + if (options.modifierKey === null) return true; // Bypass by default var m = true; switch(options.modifierKey) { case 'ctrl': m = (e.ctrlKey ? e.ctrlKey : false); break; case 'alt': m = (e.altKey ? e.altKey : false); break; case 'shift': m = (e.shiftKey ? e.shiftKey : false); break; } return m; } function getKey(e) { var k = false, c = (e.keyCode ? e.keyCode : e.which); // Handle keywords if (c == 13) k = 'enter'; // Handle letters else k = String.fromCharCode(c).toLowerCase(); return k; } function saveState() { createCookie(options.cookiePrefix + options.id, (sticky ? '1' : '0') + '-' + overlayZState + '-' + classNumber, 1); } function showOverlay() { overlay.show(); overlayVert.css({width: overlay.width()}); // hide any vertical blocks that aren't at the top of the viewport overlayVert.children('.vert').each(function () { var vCol = $(this); vCol.css('display','inline-block'); if (vCol.offset().top > vCol.parent().offset().top) { vCol.hide(); } }); } /** * Event handlers */ alreadyDown = {}; function keydownHandler(e) { var k, m, source = e.target.tagName.toLowerCase(); if ((source == 'input') || (source == 'textarea') || (source == 'select')) { return true; } m = getModifier(e); if (!m) { return true; } k = getKey(e); if (!k) { return true; } if (alreadyDown[k]) { return true; } alreadyDown[k] = true; switch(k) { case options.showGridKey: if (!overlayOn) { showOverlay(); overlayOn = true; } else if (sticky) { overlay.hide(); overlayOn = false; sticky = false; saveState(); } break; case options.holdGridKey: if (overlayOn && !sticky) { // Turn sticky overlay on sticky = true; saveState(); } break; case options.foregroundKey: if (overlayOn) { // Toggle sticky overlay z-index if (overlay.css('z-index') == overlayZForeground) { overlay.css('z-index', overlayZBackground); overlayZState = 'B'; } else { overlay.css('z-index', overlayZForeground); overlayZState = 'F'; } saveState(); } break; case options.jumpGridsKey: if (overlayOn && (options.numberOfGrids > 1)) { // Cycle through the available grids overlay.removeClass(options.classPrefix + classNumber); classNumber++; if (classNumber > options.numberOfGrids) classNumber = 1; overlay.addClass(options.classPrefix + classNumber); showOverlay(); if (/webkit/.test( navigator.userAgent.toLowerCase() )) { forceRepaint(); } saveState(); } break; } return true; } function keyupHandler(e) { var k, m = getModifier(e); if (!m) { return true; } k = getKey(e); alreadyDown[k] = false; if (k && (k == options.showGridKey) && !sticky) { overlay.hide(); overlayOn = false; } return true; } /** * Cookie functions * * By Peter-Paul Koch: * http://www.quirksmode.org/js/cookies.html */ function createCookie(name, value, days) { var date, expires = ""; if (days) { date = new Date(); date.setTime( date.getTime() + (days*24*60*60*1000) ); expires = "; expires=" + date.toGMTString(); } document.cookie = name + "=" + value + expires + "; path=/"; } function readCookie(name) { var c, ca = document.cookie.split(';'), i = 0, len = ca.length, nameEQ = name + "="; for (; i < len; i++) { c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1, c.length); } - if (c.indexOf(nameEQ) == 0) { + if (c.indexOf(nameEQ) === 0) { return c.substring(nameEQ.length, c.length); } } return null; } function eraseCookie(name) { createCookie(name, "", -1); } /** * Forces a repaint (because WebKit has issues) * http://www.sitepoint.com/forums/showthread.php?p=4538763 * http://www.phpied.com/the-new-game-show-will-it-reflow/ */ function forceRepaint() { var ss = document.styleSheets[0]; try { ss.addRule('.xxxxxx', 'position: relative'); ss.removeRule(ss.rules.length - 1); } catch(e) {} } return {}; }; /** * You can call hashgrid from your own code, but it's loaded here as * an example for your convenience. */ jQuery(document).ready(function() { var grid = new hashgrid({ numberOfGrids: 2 }); });
dotjay/hashgrid
5a810fd0a426c64122f12df20367c5e7d92764be
avoid errors with jQuery in noConflict mode
diff --git a/hashgrid.js b/hashgrid.js index e3b208f..8167b6d 100644 --- a/hashgrid.js +++ b/hashgrid.js @@ -1,435 +1,436 @@ /** * hashgrid (jQuery version, adapters are on the way) * http://github.com/dotjay/hashgrid * Version 8, 06 Oct 2012 * Written by Jon Gibbins * * Contibutors: * James Aitken, http://loonypandora.co.uk/ * Tom Arnold, http://www.tomarnold.de/ * Sean Coates, http://seancoates.com/ * Phil Dokas, http://jetless.org/ * Andrew Jaswa, http://andrewjaswa.com/ * Callum Macrae, http://lynx.io/ */ /** * @license Copyright 2011 Analog Coop Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Usage * * // The basic #grid setup looks like this * var grid = new hashgrid(); * * // But there are a whole bunch of additional options you can set * var grid = new hashgrid({ * id: 'mygrid', // set a custom id for the grid container * modifierKey: 'alt', // optional 'ctrl', 'alt' or 'shift' * showGridKey: 's', // key to show the grid * holdGridKey: 'enter', // key to hold the grid in place * foregroundKey: 'f', // key to toggle foreground/background * jumpGridsKey: 'd', // key to cycle through the grid classes * numberOfGrids: 2, // number of grid classes used * classPrefix: 'myclass', // prefix for the grid classes * cookiePrefix: 'mygrid' // prefix for the cookie name * }); */ /** * Make sure we have the library * TODO: Use an adapter */ if (typeof jQuery == "undefined") { alert("Hashgrid: jQuery not loaded. Make sure it's linked to your pages."); } /** * hashgrid overlay * @constructor */ var hashgrid = function(set) { + var $ = jQuery; var options = { id: 'grid', // id for the grid container modifierKey: null, // optional 'ctrl', 'alt' or 'shift' showGridKey: 'g', // key to show the grid holdGridKey: 'h', // key to hold the grid in place foregroundKey: 'f', // key to toggle foreground/background jumpGridsKey: 'j', // key to cycle through the grid classes numberOfGrids: 1, // number of grid classes used classPrefix: 'grid-', // prefix for the grid classes cookiePrefix: 'hashgrid'// prefix for the cookie name }, alreadyDown, classNumber = 1, gridLines, gridWidth, i, line, lineHeight, numGridLines, overlay, overlayCookie, overlayEl, overlayOn = false, overlayVert, overlayZState = 'B', overlayZBackground = -1, overlayZForeground = 9999, pageHeight, setKey, state, sticky = false, top; // Apply options if (typeof set == 'object') { for (setKey in set) { options[setKey] = set[setKey]; } } else if (typeof set == 'string') { options.id = set; } // Remove any conflicting overlay if ($('#' + options.id).length > 0) { $('#' + options.id).remove(); } // Create overlay, hidden before adding to DOM overlayEl = $('<div></div>'); overlayEl .attr('id', options.id) .css({ display: 'none', pointerEvents: 'none' }); $("body").prepend(overlayEl); overlay = $('#' + options.id); // Unless a custom z-index is set, ensure the overlay will be behind everything if (overlay.css('z-index') == 'auto') overlay.css('z-index', overlayZBackground); // Override the default overlay height with the actual page height pageHeight = parseFloat($(document).height()); overlay.height(pageHeight); // Add the first grid line so that we can measure it overlay.append('<div id="' + options.id + '-horiz" class="horiz first-line">'); // Position off-screen and display to calculate height top = overlay.css("top"); overlay.css({ top: '-999px', display: 'block' }); // Calculate the number of grid lines needed line = $('#' + options.id + '-horiz'); lineHeight = line.outerHeight(); // Hide and reset top overlay.css({ display: 'none', top: top }); // Break on zero line height if (lineHeight <= 0) { return false; } // Add the remaining grid lines numGridLines = Math.floor(pageHeight / lineHeight); gridLines = ''; for (i = numGridLines - 1; i >= 1; i--) { gridLines += '<div class="horiz"></div>'; } overlay.append(gridLines); // vertical grid overlay.append($('<div class="vert-container"></div>')); overlayVert = overlay.children('.vert-container'); gridWidth = overlay.width(); overlayVert.css({width: gridWidth, position: 'absolute', top: 0}); overlayVert.append('<div class="vert first-line">&nbsp;</div>'); // 30 is an arbitrarily large number... // can't calculate the margin width properly gridLines = ''; for (i = 0; i < 30; i++) { gridLines += '<div class="vert">&nbsp;</div>'; } overlayVert.append(gridLines); overlayVert.children() .height(pageHeight) .css({ display: 'inline-block' }); // Check for saved state overlayCookie = readCookie(options.cookiePrefix + options.id); if (typeof overlayCookie == 'string') { state = overlayCookie.split('-'); state[2] = Number(state[2]); if ((typeof state[2] == 'number') && !isNaN(state[2])) { classNumber = state[2].toFixed(0); overlay.addClass(options.classPrefix + classNumber); } if (state[1] == 'F') { overlayZState = 'F'; overlay.css('z-index', overlayZForeground); } if (state[0] == '1') { overlayOn = true; sticky = true; showOverlay(); } } else { overlay.addClass(options.classPrefix + classNumber); } // Keyboard controls $(document).bind('keydown', keydownHandler); $(document).bind('keyup', keyupHandler); /** * Helpers */ function getModifier(e) { if (options.modifierKey == null) return true; // Bypass by default var m = true; switch(options.modifierKey) { case 'ctrl': m = (e.ctrlKey ? e.ctrlKey : false); break; case 'alt': m = (e.altKey ? e.altKey : false); break; case 'shift': m = (e.shiftKey ? e.shiftKey : false); break; } return m; } function getKey(e) { var k = false, c = (e.keyCode ? e.keyCode : e.which); // Handle keywords if (c == 13) k = 'enter'; // Handle letters else k = String.fromCharCode(c).toLowerCase(); return k; } function saveState() { createCookie(options.cookiePrefix + options.id, (sticky ? '1' : '0') + '-' + overlayZState + '-' + classNumber, 1); } function showOverlay() { overlay.show(); overlayVert.css({width: overlay.width()}); // hide any vertical blocks that aren't at the top of the viewport overlayVert.children('.vert').each(function () { var vCol = $(this); vCol.css('display','inline-block'); if (vCol.offset().top > vCol.parent().offset().top) { vCol.hide(); } }); } /** * Event handlers */ alreadyDown = {}; function keydownHandler(e) { var k, m, source = e.target.tagName.toLowerCase(); if ((source == 'input') || (source == 'textarea') || (source == 'select')) { return true; } m = getModifier(e); if (!m) { return true; } k = getKey(e); if (!k) { return true; } if (alreadyDown[k]) { return true; } alreadyDown[k] = true; switch(k) { case options.showGridKey: if (!overlayOn) { showOverlay(); overlayOn = true; } else if (sticky) { overlay.hide(); overlayOn = false; sticky = false; saveState(); } break; case options.holdGridKey: if (overlayOn && !sticky) { // Turn sticky overlay on sticky = true; saveState(); } break; case options.foregroundKey: if (overlayOn) { // Toggle sticky overlay z-index if (overlay.css('z-index') == overlayZForeground) { overlay.css('z-index', overlayZBackground); overlayZState = 'B'; } else { overlay.css('z-index', overlayZForeground); overlayZState = 'F'; } saveState(); } break; case options.jumpGridsKey: if (overlayOn && (options.numberOfGrids > 1)) { // Cycle through the available grids overlay.removeClass(options.classPrefix + classNumber); classNumber++; if (classNumber > options.numberOfGrids) classNumber = 1; overlay.addClass(options.classPrefix + classNumber); showOverlay(); if (/webkit/.test( navigator.userAgent.toLowerCase() )) { forceRepaint(); } saveState(); } break; } return true; } function keyupHandler(e) { var k, m = getModifier(e); if (!m) { return true; } k = getKey(e); alreadyDown[k] = false; if (k && (k == options.showGridKey) && !sticky) { overlay.hide(); overlayOn = false; } return true; } /** * Cookie functions * * By Peter-Paul Koch: * http://www.quirksmode.org/js/cookies.html */ function createCookie(name, value, days) { var date, expires = ""; if (days) { date = new Date(); date.setTime( date.getTime() + (days*24*60*60*1000) ); expires = "; expires=" + date.toGMTString(); } document.cookie = name + "=" + value + expires + "; path=/"; } function readCookie(name) { var c, ca = document.cookie.split(';'), i = 0, len = ca.length, nameEQ = name + "="; for (; i < len; i++) { c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1, c.length); } if (c.indexOf(nameEQ) == 0) { return c.substring(nameEQ.length, c.length); } } return null; } function eraseCookie(name) { createCookie(name, "", -1); } /** * Forces a repaint (because WebKit has issues) * http://www.sitepoint.com/forums/showthread.php?p=4538763 * http://www.phpied.com/the-new-game-show-will-it-reflow/ */ function forceRepaint() { var ss = document.styleSheets[0]; try { ss.addRule('.xxxxxx', 'position: relative'); ss.removeRule(ss.rules.length - 1); } catch(e) {} } return {}; }; /** * You can call hashgrid from your own code, but it's loaded here as * an example for your convenience. */ -$(document).ready(function() { +jQuery(document).ready(function() { var grid = new hashgrid({ numberOfGrids: 2 }); });
dotjay/hashgrid
a95a041f78018bc67b848dfa94f7d820b1c7f4f8
Link to the latest hashgrid.js file. Update some links.
diff --git a/hashgrid.js b/hashgrid.js index 2827041..e3b208f 100644 --- a/hashgrid.js +++ b/hashgrid.js @@ -1,438 +1,435 @@ /** * hashgrid (jQuery version, adapters are on the way) * http://github.com/dotjay/hashgrid * Version 8, 06 Oct 2012 * Written by Jon Gibbins * * Contibutors: * James Aitken, http://loonypandora.co.uk/ * Tom Arnold, http://www.tomarnold.de/ * Sean Coates, http://seancoates.com/ * Phil Dokas, http://jetless.org/ * Andrew Jaswa, http://andrewjaswa.com/ * Callum Macrae, http://lynx.io/ */ /** * @license Copyright 2011 Analog Coop Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Usage * * // The basic #grid setup looks like this * var grid = new hashgrid(); * - * // Or you can set a custom id for your grid, e.g. #mygrid - * var grid = new hashgrid("mygrid"); - * * // But there are a whole bunch of additional options you can set * var grid = new hashgrid({ - * id: 'mygrid', // id for the grid container + * id: 'mygrid', // set a custom id for the grid container * modifierKey: 'alt', // optional 'ctrl', 'alt' or 'shift' * showGridKey: 's', // key to show the grid * holdGridKey: 'enter', // key to hold the grid in place * foregroundKey: 'f', // key to toggle foreground/background * jumpGridsKey: 'd', // key to cycle through the grid classes * numberOfGrids: 2, // number of grid classes used - * classPrefix: 'class', // prefix for the grid classes + * classPrefix: 'myclass', // prefix for the grid classes * cookiePrefix: 'mygrid' // prefix for the cookie name * }); */ /** * Make sure we have the library * TODO: Use an adapter */ if (typeof jQuery == "undefined") { alert("Hashgrid: jQuery not loaded. Make sure it's linked to your pages."); } /** * hashgrid overlay * @constructor */ var hashgrid = function(set) { var options = { id: 'grid', // id for the grid container modifierKey: null, // optional 'ctrl', 'alt' or 'shift' showGridKey: 'g', // key to show the grid holdGridKey: 'h', // key to hold the grid in place foregroundKey: 'f', // key to toggle foreground/background jumpGridsKey: 'j', // key to cycle through the grid classes numberOfGrids: 1, // number of grid classes used classPrefix: 'grid-', // prefix for the grid classes cookiePrefix: 'hashgrid'// prefix for the cookie name }, alreadyDown, classNumber = 1, gridLines, gridWidth, i, line, lineHeight, numGridLines, overlay, overlayCookie, overlayEl, overlayOn = false, overlayVert, overlayZState = 'B', overlayZBackground = -1, overlayZForeground = 9999, pageHeight, setKey, state, sticky = false, top; // Apply options if (typeof set == 'object') { for (setKey in set) { options[setKey] = set[setKey]; } } else if (typeof set == 'string') { options.id = set; } // Remove any conflicting overlay if ($('#' + options.id).length > 0) { $('#' + options.id).remove(); } // Create overlay, hidden before adding to DOM overlayEl = $('<div></div>'); overlayEl .attr('id', options.id) .css({ display: 'none', pointerEvents: 'none' }); $("body").prepend(overlayEl); overlay = $('#' + options.id); // Unless a custom z-index is set, ensure the overlay will be behind everything if (overlay.css('z-index') == 'auto') overlay.css('z-index', overlayZBackground); // Override the default overlay height with the actual page height pageHeight = parseFloat($(document).height()); overlay.height(pageHeight); // Add the first grid line so that we can measure it overlay.append('<div id="' + options.id + '-horiz" class="horiz first-line">'); // Position off-screen and display to calculate height top = overlay.css("top"); overlay.css({ top: '-999px', display: 'block' }); // Calculate the number of grid lines needed line = $('#' + options.id + '-horiz'); lineHeight = line.outerHeight(); // Hide and reset top overlay.css({ display: 'none', top: top }); // Break on zero line height if (lineHeight <= 0) { return false; } // Add the remaining grid lines numGridLines = Math.floor(pageHeight / lineHeight); gridLines = ''; for (i = numGridLines - 1; i >= 1; i--) { gridLines += '<div class="horiz"></div>'; } overlay.append(gridLines); // vertical grid overlay.append($('<div class="vert-container"></div>')); overlayVert = overlay.children('.vert-container'); gridWidth = overlay.width(); overlayVert.css({width: gridWidth, position: 'absolute', top: 0}); overlayVert.append('<div class="vert first-line">&nbsp;</div>'); // 30 is an arbitrarily large number... // can't calculate the margin width properly gridLines = ''; for (i = 0; i < 30; i++) { gridLines += '<div class="vert">&nbsp;</div>'; } overlayVert.append(gridLines); overlayVert.children() .height(pageHeight) .css({ display: 'inline-block' }); // Check for saved state overlayCookie = readCookie(options.cookiePrefix + options.id); if (typeof overlayCookie == 'string') { state = overlayCookie.split('-'); state[2] = Number(state[2]); if ((typeof state[2] == 'number') && !isNaN(state[2])) { classNumber = state[2].toFixed(0); overlay.addClass(options.classPrefix + classNumber); } if (state[1] == 'F') { overlayZState = 'F'; overlay.css('z-index', overlayZForeground); } if (state[0] == '1') { overlayOn = true; sticky = true; showOverlay(); } } else { overlay.addClass(options.classPrefix + classNumber); } // Keyboard controls $(document).bind('keydown', keydownHandler); $(document).bind('keyup', keyupHandler); /** * Helpers */ function getModifier(e) { if (options.modifierKey == null) return true; // Bypass by default var m = true; switch(options.modifierKey) { case 'ctrl': m = (e.ctrlKey ? e.ctrlKey : false); break; case 'alt': m = (e.altKey ? e.altKey : false); break; case 'shift': m = (e.shiftKey ? e.shiftKey : false); break; } return m; } function getKey(e) { var k = false, c = (e.keyCode ? e.keyCode : e.which); // Handle keywords if (c == 13) k = 'enter'; // Handle letters else k = String.fromCharCode(c).toLowerCase(); return k; } function saveState() { createCookie(options.cookiePrefix + options.id, (sticky ? '1' : '0') + '-' + overlayZState + '-' + classNumber, 1); } function showOverlay() { overlay.show(); overlayVert.css({width: overlay.width()}); // hide any vertical blocks that aren't at the top of the viewport overlayVert.children('.vert').each(function () { var vCol = $(this); vCol.css('display','inline-block'); if (vCol.offset().top > vCol.parent().offset().top) { vCol.hide(); } }); } /** * Event handlers */ alreadyDown = {}; function keydownHandler(e) { var k, m, source = e.target.tagName.toLowerCase(); if ((source == 'input') || (source == 'textarea') || (source == 'select')) { return true; } m = getModifier(e); if (!m) { return true; } k = getKey(e); if (!k) { return true; } if (alreadyDown[k]) { return true; } alreadyDown[k] = true; switch(k) { case options.showGridKey: if (!overlayOn) { showOverlay(); overlayOn = true; } else if (sticky) { overlay.hide(); overlayOn = false; sticky = false; saveState(); } break; case options.holdGridKey: if (overlayOn && !sticky) { // Turn sticky overlay on sticky = true; saveState(); } break; case options.foregroundKey: if (overlayOn) { // Toggle sticky overlay z-index if (overlay.css('z-index') == overlayZForeground) { overlay.css('z-index', overlayZBackground); overlayZState = 'B'; } else { overlay.css('z-index', overlayZForeground); overlayZState = 'F'; } saveState(); } break; case options.jumpGridsKey: if (overlayOn && (options.numberOfGrids > 1)) { // Cycle through the available grids overlay.removeClass(options.classPrefix + classNumber); classNumber++; if (classNumber > options.numberOfGrids) classNumber = 1; overlay.addClass(options.classPrefix + classNumber); showOverlay(); if (/webkit/.test( navigator.userAgent.toLowerCase() )) { forceRepaint(); } saveState(); } break; } return true; } function keyupHandler(e) { var k, m = getModifier(e); if (!m) { return true; } k = getKey(e); alreadyDown[k] = false; if (k && (k == options.showGridKey) && !sticky) { overlay.hide(); overlayOn = false; } return true; } /** * Cookie functions * * By Peter-Paul Koch: * http://www.quirksmode.org/js/cookies.html */ function createCookie(name, value, days) { var date, expires = ""; if (days) { date = new Date(); date.setTime( date.getTime() + (days*24*60*60*1000) ); expires = "; expires=" + date.toGMTString(); } document.cookie = name + "=" + value + expires + "; path=/"; } function readCookie(name) { var c, ca = document.cookie.split(';'), i = 0, len = ca.length, nameEQ = name + "="; for (; i < len; i++) { c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1, c.length); } if (c.indexOf(nameEQ) == 0) { return c.substring(nameEQ.length, c.length); } } return null; } function eraseCookie(name) { createCookie(name, "", -1); } /** * Forces a repaint (because WebKit has issues) * http://www.sitepoint.com/forums/showthread.php?p=4538763 * http://www.phpied.com/the-new-game-show-will-it-reflow/ */ function forceRepaint() { var ss = document.styleSheets[0]; try { ss.addRule('.xxxxxx', 'position: relative'); ss.removeRule(ss.rules.length - 1); } catch(e) {} } return {}; }; /** * You can call hashgrid from your own code, but it's loaded here as * an example for your convenience. */ $(document).ready(function() { var grid = new hashgrid({ numberOfGrids: 2 }); }); diff --git a/index.htm b/index.htm index 60748c8..e940185 100644 --- a/index.htm +++ b/index.htm @@ -1,461 +1,461 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>#grid</title> <style type="text/css"> /* Putting inline rules here so the document can be downloaded with style */ body{ font-size: 1em; line-height: 1.25; font-family: Arial, sans-serif; background: White; color: DimGray; margin: 0; padding: 0 20px; } #content{ font-size: 16px; line-height: 20px; position: relative; } #content{ width: 620px; margin: 0 auto; } #footer{ border-top: 1px dotted DarkGray; padding-top: 19px; } h1, h2{ color: Black; font-weight: normal; } h1{ font-size: 36px; line-height: 40px; margin: 40px 0 20px; padding-bottom: 19px; border-bottom: 1px dotted DarkGray; } h1 em{ font-style: normal; color: DarkGray; font-size: 16px; line-height: 20px; margin: 0 0 20px; } h2, h3{ font-size: 16px; font-weight: 700; line-height: 20px; margin: 0 0 20px; } h3{ font-weight: 300; } a:link, a:visited{ color: Black; text-decoration: none; padding: 0 2px; background-color: WhiteSmoke; border-bottom: 1px solid Gold; } a:focus{ outline: none; } a:focus, a:hover, a:active{ background-color: Khaki; border-bottom: 1px solid GoldenRod; } p, ul{ padding: 0; margin: 0 0 20px; } dl, ol{ padding: 0; margin: 0; } ul{ list-style: circle; } ol li{ margin-bottom: 20px; } dd{ margin: 0 0 20px 0; } del{ text-decoration: line-through; opacity: 0.75; } ins{ text-decoration: none; } code{ font-size: 14px; line-height: 1; } textarea{ font-family: 'Courier New', monospace; font-size: 14px; line-height: 20px; display: block; width: 600px; margin: 0 0 20px; padding: 0 0 0 15px; border: 0; color: Black; background: Gainsboro; border-left: 5px solid DarkGray; } #javascript-code{ height: 180px; } #css-code{ height: 1300px; } .summary em{ font-style: normal; position: absolute; color: DarkGray; right: 0; top: 18px; width: 140px; } .summary em span{ position: absolute; left: -9999px; } #download{ line-height: 60px; padding: 0 40px 0 15px; border-left: 5px solid DarkGray; background: Gainsboro; color: DimGray; } span.key{ color: Black; text-transform: uppercase; } </style> <!-- Set styles --> <style type="text/css"> /** * Grid */ #grid{ /* Dimensions - same width as your grid with gutters */ width: 980px; /* Grid (left-aligned) position: absolute; top: 0; left: 0; */ /* Grid (centered) */ position: absolute; top: 0; left: 50%; margin-left: -490px; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ #grid div.vert{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-right: 19px; } #grid div.vert.first-line{ margin-left: 19px; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ #grid div.horiz{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option in the hashgrid.js file. */ #grid.grid-1 div.vert{ /* Vertical grid line colour for grid 1 */ border-color: darkturquoise; } #grid.grid-2{ /* Adjustments */ padding: 0 160px; width: 660px; } #grid.grid-2 div.vert{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </style> </head> <body> <div id="content" role="main"> <h1>#grid <em>v8</em></h1> <p class="summary"><em>Sat, 6 Oct 2012<span>:</span></em> This is a little tool we created for our <a href="http://analog.coop/">Analog&#160;holding&#160;page</a>. It inserts a <a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a> in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit <span class="key">G</span> on your keyboard.</p> <h2>Download</h2> -<p id="download"><a href="http://github.com/dotjay/hashgrid/downloads">Download #grid</a> from <a href="http://github.com/dotjay/hashgrid">GitHub</a></p> +<p id="download"><a href="https://github.com/dotjay/hashgrid/downloads">Download #grid</a> from <a href="https://github.com/dotjay/hashgrid">GitHub</a></p> <h2 id="features">Features</h2> <ul> <li>Adaptable for all layout widths and alignments</li> <li>Adaptable for any vertical rhythm value</li> <li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li> <li>Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters</li> </ul> <p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p> <h2 id="installation">Installation</h2> <ol> -<li><h3>Copy the <a href="http://github.com/dotjay/hashgrid/blob/v7/hashgrid.js">hashgrid.js</a> script to your project</h3></li> +<li><h3>Copy the <a href="https://github.com/dotjay/hashgrid/blob/v8/hashgrid.js">hashgrid.js</a> script to your project</h3></li> <li><h3>Add the script to your page(s) just inside the <code>&#60;/body&#62;</code> tag</h3> <textarea id="javascript-code" cols="68" rows="8" readonly="readonly"> &#60;!-- Grab latest version of jQuery --&#62; &#60;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"&#62; &#60;/script&#62; &#60;!-- Include the hashgrid script --&#62; &#60;script type="text/javascript" src="hashgrid.js"&#62;&#60;/script&#62;</textarea></li> <li><h3>Add the CSS to your page(s)</h3> <textarea id="css-code" cols="68" rows="64" readonly="readonly"> /** * Grid */ #grid{ /* Dimensions - same width as your grid with gutters */ width: 980px; /* Grid (left-aligned) position: absolute; top: 0; left: 0; */ /* Grid (centered) */ position: absolute; top: 0; left: 50%; margin-left: -490px; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ #grid div.vert{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-right: 19px; } #grid div.vert.first-line{ margin-left: 19px; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ #grid div.horiz{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option in the hashgrid.js file. */ #grid.grid-1 div.vert{ /* Vertical grid line colour for grid 1 */ border-color: darkturquoise; } #grid.grid-2{ /* Adjustments */ padding: 0 160px; width: 660px; } #grid.grid-2 div.vert{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </textarea></li> <li><h3>Modify #grid to suit your needs</h3> <p>The CSS and JavaScript is annotated to help you.</p></li> </ol> <h2 id="usage">Usage</h2> <p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p> <dl> <dt><span class="key">G</span></dt> <dd>Show the grid until you release.</dd> <dt><span class="key">G</span> + <span class="key">H</span></dt> <dd>Show and hold the grid (<span class="key">G</span> will remove it again).</dd> <dt><span class="key">G</span> + <span class="key">F</span></dt> <dd>Toggle the grid to the foreground and back. Pressing <span class="key">F</span> while the grid is held also works.</dd> <dt><span class="key">G</span> + <span class="key">J</span></dt> <dd>Jump to the next grid. Pressing <span class="key">J</span> while the grid is held also works.</dd> </dl> <p><em>N.B. A cookie conveniently remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page except in Chrome v4, Safari v4, Firefox v3.6, or more recent versions.</em></p> <h2 id="release-notes">Release Notes</h2> <dl> <dt>v8&#8201;&#8212;&#8201;6 Oct 2012</dt> <dd> <ul> <li>Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="http://www.tomarnold.de/">Tom Arnold</a>.</li> <li>Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="http://lynx.io/">Callum Macrae</a>.</li> <li>Fixes to cookie handling. Thanks to <a href="http://loonypandora.co.uk/">James Aitken</a>.</li> -<li>Optimisations</li> +<li>Optimisations.</li> </ul> </dd> <dt>v7&#8201;&#8212;&#8201;11 Jun 2011</dt> <dd>Minor release: Updated license references.</dd> <dt>v6&#8201;&#8212;&#8201;10 Jun 2011</dt> <dd>Minor release: Optimisations (thanks to <a href="http://andrewjaswa.com/">Andrew Jaswa</a> for contributions), and now released under an Apache License.</dd> <dt>v5&#8201;&#8212;&#8201;3 Nov 2010</dt> <dd> <ul> <li>Vertical grid lines can now be set using CSS&#8230; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution.</li> <li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li> <li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback.</li> </ul> </dd> <dt>v4&#8201;&#8212;&#8201;29 Mar 2010</dt> <dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd> <dt>v3&#8201;&#8212;&#8201;22 Feb 2010</dt> <dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd> <dt>v2&#8201;&#8212;&#8201;2 Feb 2010</dt> <dd> <ul> <li>Keys are now more easily configured (see top of hashgrid.js).</li> <li>Fixed crash when using with disabled CSS.</li> <li>Renamed the GridOverlay object to hashgrid.</li> </ul> </dd> <dt>v1&#8201;&#8212;&#8201;21 Dec 2009</dt> <dd>First release.</dd> </dl> <h2 id="known-issues">Known Issues</h2> <ul> <li><del>IE 8: Fully functional, but the default <span class="key">ALT</span> + <span class="key">G</span> + <span class="key">ENTER</span> shortcut puts IE into full screen mode. Hit <span class="key">ALT</span> + <span class="key">ENTER</span> to toggle full screen mode off again.</del><ins datetime="2010-02-22"> The default keyboard shortcuts have been changed.</ins></li> <li>IE 6: The grid is always in the foreground.</li> <li>Opera 9/10: Using <span class="key">CTRL</span> or <span class="key">ALT</span> as a modifier key will not work due to different key handling by the browser.</li> </ul> <h2 id="license">License</h2> <p>Copyright 2011 Analog Coop Limited</p> <p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br /><br /> <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a></p> <p>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.</p> <p>This essentially means that you&#8217;re free to copy, modify and distribute it for any project so long as you provide clear attribution to Analog Coop Limited. <a href="http://analog.coop/#talk-to-us">Contact us</a> if you need a different license.</p> <div id="footer" role="contentinfo"> <p>#grid is an <a href="http://analog.coop/">Analog</a> gig. It was conceived by <a href="http://jontangerine.com/">Jon Tan</a>, and built by <a href="http://accessibility.co.uk/">Jon Gibbins</a>, in cahoots with our <a href="http://analog.coop#is">fine friends</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p> </div> </div> <!-- Grab latest version of jQuery --> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script> <!-- Include the hashgrid script --> <script type="text/javascript" src="hashgrid.js"></script> </body> </html>
dotjay/hashgrid
d7bce3db6a9c95dae5874a805b80f1d3e08d3941
Release v8
diff --git a/index.htm b/index.htm index 3d139c9..60748c8 100644 --- a/index.htm +++ b/index.htm @@ -1,446 +1,461 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>#grid</title> <style type="text/css"> /* Putting inline rules here so the document can be downloaded with style */ body{ font-size: 1em; line-height: 1.25; font-family: Arial, sans-serif; background: White; color: DimGray; margin: 0; padding: 0 20px; } #content{ font-size: 16px; line-height: 20px; position: relative; } #content{ width: 620px; margin: 0 auto; } #footer{ border-top: 1px dotted DarkGray; padding-top: 19px; } h1, h2{ color: Black; font-weight: normal; } h1{ font-size: 36px; line-height: 40px; margin: 40px 0 20px; padding-bottom: 19px; border-bottom: 1px dotted DarkGray; } h1 em{ font-style: normal; color: DarkGray; font-size: 16px; line-height: 20px; margin: 0 0 20px; } h2, h3{ font-size: 16px; font-weight: 700; line-height: 20px; margin: 0 0 20px; } h3{ font-weight: 300; } a:link, a:visited{ color: Black; text-decoration: none; padding: 0 2px; background-color: WhiteSmoke; border-bottom: 1px solid Gold; } a:focus{ outline: none; } a:focus, a:hover, a:active{ background-color: Khaki; border-bottom: 1px solid GoldenRod; } p, ul{ padding: 0; margin: 0 0 20px; } dl, ol{ padding: 0; margin: 0; } ul{ list-style: circle; } ol li{ margin-bottom: 20px; } dd{ margin: 0 0 20px 0; } del{ text-decoration: line-through; opacity: 0.75; } ins{ text-decoration: none; } code{ font-size: 14px; line-height: 1; } textarea{ font-family: 'Courier New', monospace; font-size: 14px; line-height: 20px; display: block; width: 600px; margin: 0 0 20px; padding: 0 0 0 15px; border: 0; color: Black; background: Gainsboro; border-left: 5px solid DarkGray; } #javascript-code{ height: 180px; } #css-code{ height: 1300px; } .summary em{ font-style: normal; position: absolute; color: DarkGray; right: 0; top: 18px; width: 140px; } .summary em span{ position: absolute; left: -9999px; } #download{ line-height: 60px; padding: 0 40px 0 15px; border-left: 5px solid DarkGray; background: Gainsboro; color: DimGray; } span.key{ color: Black; text-transform: uppercase; } </style> <!-- Set styles --> <style type="text/css"> /** * Grid */ #grid{ /* Dimensions - same width as your grid with gutters */ width: 980px; /* Grid (left-aligned) position: absolute; top: 0; left: 0; */ /* Grid (centered) */ position: absolute; top: 0; left: 50%; margin-left: -490px; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ #grid div.vert{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-right: 19px; } #grid div.vert.first-line{ margin-left: 19px; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ #grid div.horiz{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option in the hashgrid.js file. */ #grid.grid-1 div.vert{ /* Vertical grid line colour for grid 1 */ border-color: darkturquoise; } #grid.grid-2{ /* Adjustments */ padding: 0 160px; width: 660px; } #grid.grid-2 div.vert{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </style> </head> <body> <div id="content" role="main"> -<h1>#grid <em>v7</em></h1> +<h1>#grid <em>v8</em></h1> -<p class="summary"><em>Sat, 11 Jun 2011<span>:</span></em> This is a little tool we created for our <a href="http://analog.coop/">Analog&#160;holding&#160;page</a>. It inserts a <a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a> in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit <span class="key">G</span> on your keyboard.</p> +<p class="summary"><em>Sat, 6 Oct 2012<span>:</span></em> This is a little tool we created for our <a href="http://analog.coop/">Analog&#160;holding&#160;page</a>. It inserts a <a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a> in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit <span class="key">G</span> on your keyboard.</p> <h2>Download</h2> <p id="download"><a href="http://github.com/dotjay/hashgrid/downloads">Download #grid</a> from <a href="http://github.com/dotjay/hashgrid">GitHub</a></p> <h2 id="features">Features</h2> <ul> <li>Adaptable for all layout widths and alignments</li> <li>Adaptable for any vertical rhythm value</li> <li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li> <li>Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters</li> </ul> <p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p> <h2 id="installation">Installation</h2> <ol> <li><h3>Copy the <a href="http://github.com/dotjay/hashgrid/blob/v7/hashgrid.js">hashgrid.js</a> script to your project</h3></li> <li><h3>Add the script to your page(s) just inside the <code>&#60;/body&#62;</code> tag</h3> <textarea id="javascript-code" cols="68" rows="8" readonly="readonly"> &#60;!-- Grab latest version of jQuery --&#62; &#60;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"&#62; &#60;/script&#62; &#60;!-- Include the hashgrid script --&#62; &#60;script type="text/javascript" src="hashgrid.js"&#62;&#60;/script&#62;</textarea></li> <li><h3>Add the CSS to your page(s)</h3> <textarea id="css-code" cols="68" rows="64" readonly="readonly"> /** * Grid */ #grid{ /* Dimensions - same width as your grid with gutters */ width: 980px; /* Grid (left-aligned) position: absolute; top: 0; left: 0; */ /* Grid (centered) */ position: absolute; top: 0; left: 50%; margin-left: -490px; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ #grid div.vert{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-right: 19px; } #grid div.vert.first-line{ margin-left: 19px; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ #grid div.horiz{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option in the hashgrid.js file. */ #grid.grid-1 div.vert{ /* Vertical grid line colour for grid 1 */ border-color: darkturquoise; } #grid.grid-2{ /* Adjustments */ padding: 0 160px; width: 660px; } #grid.grid-2 div.vert{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </textarea></li> <li><h3>Modify #grid to suit your needs</h3> <p>The CSS and JavaScript is annotated to help you.</p></li> </ol> <h2 id="usage">Usage</h2> <p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p> <dl> <dt><span class="key">G</span></dt> <dd>Show the grid until you release.</dd> <dt><span class="key">G</span> + <span class="key">H</span></dt> <dd>Show and hold the grid (<span class="key">G</span> will remove it again).</dd> <dt><span class="key">G</span> + <span class="key">F</span></dt> <dd>Toggle the grid to the foreground and back. Pressing <span class="key">F</span> while the grid is held also works.</dd> <dt><span class="key">G</span> + <span class="key">J</span></dt> <dd>Jump to the next grid. Pressing <span class="key">J</span> while the grid is held also works.</dd> </dl> <p><em>N.B. A cookie conveniently remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page except in Chrome v4, Safari v4, Firefox v3.6, or more recent versions.</em></p> <h2 id="release-notes">Release Notes</h2> <dl> +<dt>v8&#8201;&#8212;&#8201;6 Oct 2012</dt> +<dd> +<ul> +<li>Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="http://www.tomarnold.de/">Tom Arnold</a>.</li> +<li>Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="http://lynx.io/">Callum Macrae</a>.</li> +<li>Fixes to cookie handling. Thanks to <a href="http://loonypandora.co.uk/">James Aitken</a>.</li> +<li>Optimisations</li> +</ul> +</dd> <dt>v7&#8201;&#8212;&#8201;11 Jun 2011</dt> <dd>Minor release: Updated license references.</dd> <dt>v6&#8201;&#8212;&#8201;10 Jun 2011</dt> -<dd>Minor release: Optimisations, and now released under an Apache License.</dd> +<dd>Minor release: Optimisations (thanks to <a href="http://andrewjaswa.com/">Andrew Jaswa</a> for contributions), and now released under an Apache License.</dd> <dt>v5&#8201;&#8212;&#8201;3 Nov 2010</dt> <dd> <ul> <li>Vertical grid lines can now be set using CSS&#8230; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution.</li> <li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li> <li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback.</li> </ul> </dd> <dt>v4&#8201;&#8212;&#8201;29 Mar 2010</dt> <dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd> <dt>v3&#8201;&#8212;&#8201;22 Feb 2010</dt> <dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd> <dt>v2&#8201;&#8212;&#8201;2 Feb 2010</dt> -<dd>Keys are now more easily configured (see top of hashgrid.js). Renamed the GridOverlay object to hashgrid. Fixed crash when using with disabled CSS.</dd> +<dd> +<ul> +<li>Keys are now more easily configured (see top of hashgrid.js).</li> +<li>Fixed crash when using with disabled CSS.</li> +<li>Renamed the GridOverlay object to hashgrid.</li> +</ul> +</dd> <dt>v1&#8201;&#8212;&#8201;21 Dec 2009</dt> <dd>First release.</dd> </dl> <h2 id="known-issues">Known Issues</h2> <ul> <li><del>IE 8: Fully functional, but the default <span class="key">ALT</span> + <span class="key">G</span> + <span class="key">ENTER</span> shortcut puts IE into full screen mode. Hit <span class="key">ALT</span> + <span class="key">ENTER</span> to toggle full screen mode off again.</del><ins datetime="2010-02-22"> The default keyboard shortcuts have been changed.</ins></li> <li>IE 6: The grid is always in the foreground.</li> <li>Opera 9/10: Using <span class="key">CTRL</span> or <span class="key">ALT</span> as a modifier key will not work due to different key handling by the browser.</li> </ul> <h2 id="license">License</h2> <p>Copyright 2011 Analog Coop Limited</p> <p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br /><br /> <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a></p> <p>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.</p> <p>This essentially means that you&#8217;re free to copy, modify and distribute it for any project so long as you provide clear attribution to Analog Coop Limited. <a href="http://analog.coop/#talk-to-us">Contact us</a> if you need a different license.</p> <div id="footer" role="contentinfo"> <p>#grid is an <a href="http://analog.coop/">Analog</a> gig. It was conceived by <a href="http://jontangerine.com/">Jon Tan</a>, and built by <a href="http://accessibility.co.uk/">Jon Gibbins</a>, in cahoots with our <a href="http://analog.coop#is">fine friends</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p> </div> </div> <!-- Grab latest version of jQuery --> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script> <!-- Include the hashgrid script --> <script type="text/javascript" src="hashgrid.js"></script> </body> </html>
dotjay/hashgrid
41b4d92eef96887158167aae6b96d1018711c322
Updating head comment with new version number and additional contributor thanks.
diff --git a/hashgrid.js b/hashgrid.js index ff1743f..2827041 100644 --- a/hashgrid.js +++ b/hashgrid.js @@ -1,435 +1,438 @@ /** - * hashgrid (jQuery version) + * hashgrid (jQuery version, adapters are on the way) * http://github.com/dotjay/hashgrid - * Version 7, 11 Jun 2011 - * Written by Jon Gibbins at Analog, http://analog.coop/ + * Version 8, 06 Oct 2012 + * Written by Jon Gibbins * * Contibutors: + * James Aitken, http://loonypandora.co.uk/ + * Tom Arnold, http://www.tomarnold.de/ * Sean Coates, http://seancoates.com/ * Phil Dokas, http://jetless.org/ * Andrew Jaswa, http://andrewjaswa.com/ + * Callum Macrae, http://lynx.io/ */ /** * @license Copyright 2011 Analog Coop Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Usage * * // The basic #grid setup looks like this * var grid = new hashgrid(); * * // Or you can set a custom id for your grid, e.g. #mygrid * var grid = new hashgrid("mygrid"); * * // But there are a whole bunch of additional options you can set * var grid = new hashgrid({ * id: 'mygrid', // id for the grid container * modifierKey: 'alt', // optional 'ctrl', 'alt' or 'shift' * showGridKey: 's', // key to show the grid * holdGridKey: 'enter', // key to hold the grid in place * foregroundKey: 'f', // key to toggle foreground/background * jumpGridsKey: 'd', // key to cycle through the grid classes * numberOfGrids: 2, // number of grid classes used * classPrefix: 'class', // prefix for the grid classes * cookiePrefix: 'mygrid' // prefix for the cookie name * }); */ /** * Make sure we have the library * TODO: Use an adapter */ if (typeof jQuery == "undefined") { alert("Hashgrid: jQuery not loaded. Make sure it's linked to your pages."); } /** * hashgrid overlay * @constructor */ var hashgrid = function(set) { var options = { id: 'grid', // id for the grid container modifierKey: null, // optional 'ctrl', 'alt' or 'shift' showGridKey: 'g', // key to show the grid holdGridKey: 'h', // key to hold the grid in place foregroundKey: 'f', // key to toggle foreground/background jumpGridsKey: 'j', // key to cycle through the grid classes numberOfGrids: 1, // number of grid classes used classPrefix: 'grid-', // prefix for the grid classes cookiePrefix: 'hashgrid'// prefix for the cookie name }, alreadyDown, classNumber = 1, gridLines, gridWidth, i, line, lineHeight, numGridLines, overlay, overlayCookie, overlayEl, overlayOn = false, overlayVert, overlayZState = 'B', overlayZBackground = -1, overlayZForeground = 9999, pageHeight, setKey, state, sticky = false, top; // Apply options if (typeof set == 'object') { for (setKey in set) { options[setKey] = set[setKey]; } } else if (typeof set == 'string') { options.id = set; } // Remove any conflicting overlay if ($('#' + options.id).length > 0) { $('#' + options.id).remove(); } // Create overlay, hidden before adding to DOM overlayEl = $('<div></div>'); overlayEl .attr('id', options.id) .css({ display: 'none', pointerEvents: 'none' }); $("body").prepend(overlayEl); overlay = $('#' + options.id); // Unless a custom z-index is set, ensure the overlay will be behind everything if (overlay.css('z-index') == 'auto') overlay.css('z-index', overlayZBackground); // Override the default overlay height with the actual page height pageHeight = parseFloat($(document).height()); overlay.height(pageHeight); // Add the first grid line so that we can measure it overlay.append('<div id="' + options.id + '-horiz" class="horiz first-line">'); // Position off-screen and display to calculate height top = overlay.css("top"); overlay.css({ top: '-999px', display: 'block' }); // Calculate the number of grid lines needed line = $('#' + options.id + '-horiz'); lineHeight = line.outerHeight(); // Hide and reset top overlay.css({ display: 'none', top: top }); // Break on zero line height if (lineHeight <= 0) { return false; } // Add the remaining grid lines numGridLines = Math.floor(pageHeight / lineHeight); gridLines = ''; for (i = numGridLines - 1; i >= 1; i--) { gridLines += '<div class="horiz"></div>'; } overlay.append(gridLines); // vertical grid overlay.append($('<div class="vert-container"></div>')); overlayVert = overlay.children('.vert-container'); gridWidth = overlay.width(); overlayVert.css({width: gridWidth, position: 'absolute', top: 0}); overlayVert.append('<div class="vert first-line">&nbsp;</div>'); // 30 is an arbitrarily large number... // can't calculate the margin width properly gridLines = ''; for (i = 0; i < 30; i++) { gridLines += '<div class="vert">&nbsp;</div>'; } overlayVert.append(gridLines); overlayVert.children() .height(pageHeight) .css({ display: 'inline-block' }); // Check for saved state overlayCookie = readCookie(options.cookiePrefix + options.id); if (typeof overlayCookie == 'string') { state = overlayCookie.split('-'); state[2] = Number(state[2]); if ((typeof state[2] == 'number') && !isNaN(state[2])) { classNumber = state[2].toFixed(0); overlay.addClass(options.classPrefix + classNumber); } if (state[1] == 'F') { overlayZState = 'F'; overlay.css('z-index', overlayZForeground); } if (state[0] == '1') { overlayOn = true; sticky = true; showOverlay(); } } else { overlay.addClass(options.classPrefix + classNumber); } // Keyboard controls $(document).bind('keydown', keydownHandler); $(document).bind('keyup', keyupHandler); /** * Helpers */ function getModifier(e) { if (options.modifierKey == null) return true; // Bypass by default var m = true; switch(options.modifierKey) { case 'ctrl': m = (e.ctrlKey ? e.ctrlKey : false); break; case 'alt': m = (e.altKey ? e.altKey : false); break; case 'shift': m = (e.shiftKey ? e.shiftKey : false); break; } return m; } function getKey(e) { var k = false, c = (e.keyCode ? e.keyCode : e.which); // Handle keywords if (c == 13) k = 'enter'; // Handle letters else k = String.fromCharCode(c).toLowerCase(); return k; } function saveState() { createCookie(options.cookiePrefix + options.id, (sticky ? '1' : '0') + '-' + overlayZState + '-' + classNumber, 1); } function showOverlay() { overlay.show(); overlayVert.css({width: overlay.width()}); // hide any vertical blocks that aren't at the top of the viewport overlayVert.children('.vert').each(function () { var vCol = $(this); vCol.css('display','inline-block'); if (vCol.offset().top > vCol.parent().offset().top) { vCol.hide(); } }); } /** * Event handlers */ alreadyDown = {}; function keydownHandler(e) { var k, m, source = e.target.tagName.toLowerCase(); if ((source == 'input') || (source == 'textarea') || (source == 'select')) { return true; } m = getModifier(e); if (!m) { return true; } k = getKey(e); if (!k) { return true; } if (alreadyDown[k]) { return true; } alreadyDown[k] = true; switch(k) { case options.showGridKey: if (!overlayOn) { showOverlay(); overlayOn = true; } else if (sticky) { overlay.hide(); overlayOn = false; sticky = false; saveState(); } break; case options.holdGridKey: if (overlayOn && !sticky) { // Turn sticky overlay on sticky = true; saveState(); } break; case options.foregroundKey: if (overlayOn) { // Toggle sticky overlay z-index if (overlay.css('z-index') == overlayZForeground) { overlay.css('z-index', overlayZBackground); overlayZState = 'B'; } else { overlay.css('z-index', overlayZForeground); overlayZState = 'F'; } saveState(); } break; case options.jumpGridsKey: if (overlayOn && (options.numberOfGrids > 1)) { // Cycle through the available grids overlay.removeClass(options.classPrefix + classNumber); classNumber++; if (classNumber > options.numberOfGrids) classNumber = 1; overlay.addClass(options.classPrefix + classNumber); showOverlay(); if (/webkit/.test( navigator.userAgent.toLowerCase() )) { forceRepaint(); } saveState(); } break; } return true; } function keyupHandler(e) { var k, m = getModifier(e); if (!m) { return true; } k = getKey(e); alreadyDown[k] = false; if (k && (k == options.showGridKey) && !sticky) { overlay.hide(); overlayOn = false; } return true; } /** * Cookie functions * * By Peter-Paul Koch: * http://www.quirksmode.org/js/cookies.html */ function createCookie(name, value, days) { var date, expires = ""; if (days) { date = new Date(); date.setTime( date.getTime() + (days*24*60*60*1000) ); expires = "; expires=" + date.toGMTString(); } document.cookie = name + "=" + value + expires + "; path=/"; } function readCookie(name) { var c, ca = document.cookie.split(';'), i = 0, len = ca.length, nameEQ = name + "="; for (; i < len; i++) { c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1, c.length); } if (c.indexOf(nameEQ) == 0) { return c.substring(nameEQ.length, c.length); } } return null; } function eraseCookie(name) { createCookie(name, "", -1); } /** * Forces a repaint (because WebKit has issues) * http://www.sitepoint.com/forums/showthread.php?p=4538763 * http://www.phpied.com/the-new-game-show-will-it-reflow/ */ function forceRepaint() { var ss = document.styleSheets[0]; try { ss.addRule('.xxxxxx', 'position: relative'); ss.removeRule(ss.rules.length - 1); } catch(e) {} } return {}; }; /** * You can call hashgrid from your own code, but it's loaded here as * an example for your convenience. */ $(document).ready(function() { var grid = new hashgrid({ numberOfGrids: 2 }); });
dotjay/hashgrid
7333d7c27155f1c8cb51130c03ebcf5d31e49943
Linting
diff --git a/hashgrid.js b/hashgrid.js index 773655f..ff1743f 100644 --- a/hashgrid.js +++ b/hashgrid.js @@ -1,434 +1,435 @@ /** * hashgrid (jQuery version) * http://github.com/dotjay/hashgrid * Version 7, 11 Jun 2011 * Written by Jon Gibbins at Analog, http://analog.coop/ * * Contibutors: * Sean Coates, http://seancoates.com/ * Phil Dokas, http://jetless.org/ * Andrew Jaswa, http://andrewjaswa.com/ */ /** * @license Copyright 2011 Analog Coop Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Usage * * // The basic #grid setup looks like this * var grid = new hashgrid(); * * // Or you can set a custom id for your grid, e.g. #mygrid * var grid = new hashgrid("mygrid"); * * // But there are a whole bunch of additional options you can set * var grid = new hashgrid({ * id: 'mygrid', // id for the grid container * modifierKey: 'alt', // optional 'ctrl', 'alt' or 'shift' * showGridKey: 's', // key to show the grid * holdGridKey: 'enter', // key to hold the grid in place * foregroundKey: 'f', // key to toggle foreground/background * jumpGridsKey: 'd', // key to cycle through the grid classes * numberOfGrids: 2, // number of grid classes used * classPrefix: 'class', // prefix for the grid classes * cookiePrefix: 'mygrid' // prefix for the cookie name * }); */ /** * Make sure we have the library * TODO: Use an adapter */ if (typeof jQuery == "undefined") { alert("Hashgrid: jQuery not loaded. Make sure it's linked to your pages."); } /** * hashgrid overlay * @constructor */ var hashgrid = function(set) { var options = { id: 'grid', // id for the grid container modifierKey: null, // optional 'ctrl', 'alt' or 'shift' showGridKey: 'g', // key to show the grid holdGridKey: 'h', // key to hold the grid in place foregroundKey: 'f', // key to toggle foreground/background jumpGridsKey: 'j', // key to cycle through the grid classes numberOfGrids: 1, // number of grid classes used classPrefix: 'grid-', // prefix for the grid classes cookiePrefix: 'hashgrid'// prefix for the cookie name }, + alreadyDown, classNumber = 1, gridLines, gridWidth, i, line, lineHeight, numGridLines, overlay, overlayCookie, overlayEl, overlayOn = false, overlayVert, overlayZState = 'B', overlayZBackground = -1, overlayZForeground = 9999, pageHeight, setKey, state, sticky = false, top; // Apply options if (typeof set == 'object') { for (setKey in set) { options[setKey] = set[setKey]; } } else if (typeof set == 'string') { options.id = set; } // Remove any conflicting overlay if ($('#' + options.id).length > 0) { $('#' + options.id).remove(); } // Create overlay, hidden before adding to DOM overlayEl = $('<div></div>'); overlayEl .attr('id', options.id) .css({ display: 'none', pointerEvents: 'none' }); $("body").prepend(overlayEl); overlay = $('#' + options.id); // Unless a custom z-index is set, ensure the overlay will be behind everything if (overlay.css('z-index') == 'auto') overlay.css('z-index', overlayZBackground); // Override the default overlay height with the actual page height pageHeight = parseFloat($(document).height()); overlay.height(pageHeight); // Add the first grid line so that we can measure it overlay.append('<div id="' + options.id + '-horiz" class="horiz first-line">'); // Position off-screen and display to calculate height top = overlay.css("top"); overlay.css({ top: '-999px', display: 'block' }); // Calculate the number of grid lines needed line = $('#' + options.id + '-horiz'); lineHeight = line.outerHeight(); // Hide and reset top overlay.css({ display: 'none', top: top }); // Break on zero line height if (lineHeight <= 0) { return false; } // Add the remaining grid lines numGridLines = Math.floor(pageHeight / lineHeight); gridLines = ''; for (i = numGridLines - 1; i >= 1; i--) { gridLines += '<div class="horiz"></div>'; } overlay.append(gridLines); // vertical grid overlay.append($('<div class="vert-container"></div>')); overlayVert = overlay.children('.vert-container'); gridWidth = overlay.width(); overlayVert.css({width: gridWidth, position: 'absolute', top: 0}); overlayVert.append('<div class="vert first-line">&nbsp;</div>'); // 30 is an arbitrarily large number... // can't calculate the margin width properly gridLines = ''; for (i = 0; i < 30; i++) { gridLines += '<div class="vert">&nbsp;</div>'; } overlayVert.append(gridLines); overlayVert.children() .height(pageHeight) .css({ display: 'inline-block' }); // Check for saved state overlayCookie = readCookie(options.cookiePrefix + options.id); if (typeof overlayCookie == 'string') { state = overlayCookie.split('-'); state[2] = Number(state[2]); if ((typeof state[2] == 'number') && !isNaN(state[2])) { classNumber = state[2].toFixed(0); overlay.addClass(options.classPrefix + classNumber); } if (state[1] == 'F') { overlayZState = 'F'; overlay.css('z-index', overlayZForeground); } if (state[0] == '1') { overlayOn = true; sticky = true; showOverlay(); } } else { overlay.addClass(options.classPrefix + classNumber); } // Keyboard controls $(document).bind('keydown', keydownHandler); $(document).bind('keyup', keyupHandler); /** * Helpers */ function getModifier(e) { if (options.modifierKey == null) return true; // Bypass by default var m = true; switch(options.modifierKey) { case 'ctrl': m = (e.ctrlKey ? e.ctrlKey : false); break; case 'alt': m = (e.altKey ? e.altKey : false); break; case 'shift': m = (e.shiftKey ? e.shiftKey : false); break; } return m; } function getKey(e) { var k = false, c = (e.keyCode ? e.keyCode : e.which); // Handle keywords if (c == 13) k = 'enter'; // Handle letters else k = String.fromCharCode(c).toLowerCase(); return k; } function saveState() { createCookie(options.cookiePrefix + options.id, (sticky ? '1' : '0') + '-' + overlayZState + '-' + classNumber, 1); } function showOverlay() { overlay.show(); overlayVert.css({width: overlay.width()}); // hide any vertical blocks that aren't at the top of the viewport overlayVert.children('.vert').each(function () { var vCol = $(this); vCol.css('display','inline-block'); if (vCol.offset().top > vCol.parent().offset().top) { vCol.hide(); } }); } /** * Event handlers */ - var alreadyDown = {}; + alreadyDown = {}; function keydownHandler(e) { var k, m, source = e.target.tagName.toLowerCase(); if ((source == 'input') || (source == 'textarea') || (source == 'select')) { return true; } m = getModifier(e); if (!m) { return true; } k = getKey(e); if (!k) { return true; } if (alreadyDown[k]) { - return; + return true; } alreadyDown[k] = true; switch(k) { case options.showGridKey: if (!overlayOn) { showOverlay(); overlayOn = true; } else if (sticky) { overlay.hide(); overlayOn = false; sticky = false; saveState(); } break; case options.holdGridKey: if (overlayOn && !sticky) { // Turn sticky overlay on sticky = true; saveState(); } break; case options.foregroundKey: if (overlayOn) { // Toggle sticky overlay z-index if (overlay.css('z-index') == overlayZForeground) { overlay.css('z-index', overlayZBackground); overlayZState = 'B'; } else { overlay.css('z-index', overlayZForeground); overlayZState = 'F'; } saveState(); } break; case options.jumpGridsKey: if (overlayOn && (options.numberOfGrids > 1)) { // Cycle through the available grids overlay.removeClass(options.classPrefix + classNumber); classNumber++; if (classNumber > options.numberOfGrids) classNumber = 1; overlay.addClass(options.classPrefix + classNumber); showOverlay(); if (/webkit/.test( navigator.userAgent.toLowerCase() )) { forceRepaint(); } saveState(); } break; } return true; } function keyupHandler(e) { var k, m = getModifier(e); if (!m) { return true; } k = getKey(e); alreadyDown[k] = false; if (k && (k == options.showGridKey) && !sticky) { overlay.hide(); overlayOn = false; } return true; } /** * Cookie functions * * By Peter-Paul Koch: * http://www.quirksmode.org/js/cookies.html */ function createCookie(name, value, days) { var date, expires = ""; if (days) { date = new Date(); date.setTime( date.getTime() + (days*24*60*60*1000) ); expires = "; expires=" + date.toGMTString(); } document.cookie = name + "=" + value + expires + "; path=/"; } function readCookie(name) { var c, ca = document.cookie.split(';'), i = 0, len = ca.length, nameEQ = name + "="; for (; i < len; i++) { c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1, c.length); } if (c.indexOf(nameEQ) == 0) { return c.substring(nameEQ.length, c.length); } } return null; } function eraseCookie(name) { createCookie(name, "", -1); } /** * Forces a repaint (because WebKit has issues) * http://www.sitepoint.com/forums/showthread.php?p=4538763 * http://www.phpied.com/the-new-game-show-will-it-reflow/ */ function forceRepaint() { var ss = document.styleSheets[0]; try { ss.addRule('.xxxxxx', 'position: relative'); ss.removeRule(ss.rules.length - 1); } catch(e) {} } return {}; }; /** * You can call hashgrid from your own code, but it's loaded here as * an example for your convenience. */ $(document).ready(function() { var grid = new hashgrid({ numberOfGrids: 2 }); });
dotjay/hashgrid
514dbc910806ab84c49a152bfbe281f85fdc7115
Made an improvement so that keys being held down won't kill anything.
diff --git a/hashgrid.js b/hashgrid.js index 5419b7c..773655f 100644 --- a/hashgrid.js +++ b/hashgrid.js @@ -1,426 +1,434 @@ /** * hashgrid (jQuery version) * http://github.com/dotjay/hashgrid - * Version 6, 10 Jun 2011 + * Version 7, 11 Jun 2011 * Written by Jon Gibbins at Analog, http://analog.coop/ * * Contibutors: * Sean Coates, http://seancoates.com/ * Phil Dokas, http://jetless.org/ * Andrew Jaswa, http://andrewjaswa.com/ */ /** * @license Copyright 2011 Analog Coop Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Usage * * // The basic #grid setup looks like this * var grid = new hashgrid(); * * // Or you can set a custom id for your grid, e.g. #mygrid * var grid = new hashgrid("mygrid"); * * // But there are a whole bunch of additional options you can set * var grid = new hashgrid({ * id: 'mygrid', // id for the grid container * modifierKey: 'alt', // optional 'ctrl', 'alt' or 'shift' * showGridKey: 's', // key to show the grid * holdGridKey: 'enter', // key to hold the grid in place * foregroundKey: 'f', // key to toggle foreground/background * jumpGridsKey: 'd', // key to cycle through the grid classes * numberOfGrids: 2, // number of grid classes used * classPrefix: 'class', // prefix for the grid classes * cookiePrefix: 'mygrid' // prefix for the cookie name * }); */ /** * Make sure we have the library * TODO: Use an adapter */ if (typeof jQuery == "undefined") { alert("Hashgrid: jQuery not loaded. Make sure it's linked to your pages."); } /** * hashgrid overlay * @constructor */ var hashgrid = function(set) { var options = { id: 'grid', // id for the grid container modifierKey: null, // optional 'ctrl', 'alt' or 'shift' showGridKey: 'g', // key to show the grid holdGridKey: 'h', // key to hold the grid in place foregroundKey: 'f', // key to toggle foreground/background jumpGridsKey: 'j', // key to cycle through the grid classes numberOfGrids: 1, // number of grid classes used classPrefix: 'grid-', // prefix for the grid classes cookiePrefix: 'hashgrid'// prefix for the cookie name }, classNumber = 1, gridLines, gridWidth, i, line, lineHeight, numGridLines, overlay, overlayCookie, overlayEl, overlayOn = false, overlayVert, overlayZState = 'B', overlayZBackground = -1, overlayZForeground = 9999, pageHeight, setKey, state, sticky = false, top; // Apply options if (typeof set == 'object') { for (setKey in set) { options[setKey] = set[setKey]; } } else if (typeof set == 'string') { options.id = set; } // Remove any conflicting overlay if ($('#' + options.id).length > 0) { $('#' + options.id).remove(); } // Create overlay, hidden before adding to DOM overlayEl = $('<div></div>'); overlayEl .attr('id', options.id) .css({ display: 'none', - 'pointer-events': 'none' + pointerEvents: 'none' }); $("body").prepend(overlayEl); overlay = $('#' + options.id); // Unless a custom z-index is set, ensure the overlay will be behind everything if (overlay.css('z-index') == 'auto') overlay.css('z-index', overlayZBackground); // Override the default overlay height with the actual page height pageHeight = parseFloat($(document).height()); overlay.height(pageHeight); // Add the first grid line so that we can measure it overlay.append('<div id="' + options.id + '-horiz" class="horiz first-line">'); // Position off-screen and display to calculate height top = overlay.css("top"); overlay.css({ - top: "-999px", - display: "block" + top: '-999px', + display: 'block' }); // Calculate the number of grid lines needed line = $('#' + options.id + '-horiz'); lineHeight = line.outerHeight(); // Hide and reset top overlay.css({ - display: "none", + display: 'none', top: top }); // Break on zero line height if (lineHeight <= 0) { return false; } // Add the remaining grid lines numGridLines = Math.floor(pageHeight / lineHeight); gridLines = ''; for (i = numGridLines - 1; i >= 1; i--) { gridLines += '<div class="horiz"></div>'; } overlay.append(gridLines); // vertical grid overlay.append($('<div class="vert-container"></div>')); overlayVert = overlay.children('.vert-container'); gridWidth = overlay.width(); overlayVert.css({width: gridWidth, position: 'absolute', top: 0}); overlayVert.append('<div class="vert first-line">&nbsp;</div>'); // 30 is an arbitrarily large number... // can't calculate the margin width properly gridLines = ''; for (i = 0; i < 30; i++) { gridLines += '<div class="vert">&nbsp;</div>'; } overlayVert.append(gridLines); overlayVert.children() .height(pageHeight) .css({ display: 'inline-block' }); // Check for saved state overlayCookie = readCookie(options.cookiePrefix + options.id); if (typeof overlayCookie == 'string') { state = overlayCookie.split('-'); state[2] = Number(state[2]); if ((typeof state[2] == 'number') && !isNaN(state[2])) { classNumber = state[2].toFixed(0); overlay.addClass(options.classPrefix + classNumber); } if (state[1] == 'F') { overlayZState = 'F'; overlay.css('z-index', overlayZForeground); } if (state[0] == '1') { overlayOn = true; sticky = true; showOverlay(); } } else { overlay.addClass(options.classPrefix + classNumber); } // Keyboard controls $(document).bind('keydown', keydownHandler); $(document).bind('keyup', keyupHandler); /** * Helpers */ function getModifier(e) { if (options.modifierKey == null) return true; // Bypass by default var m = true; switch(options.modifierKey) { case 'ctrl': m = (e.ctrlKey ? e.ctrlKey : false); break; case 'alt': m = (e.altKey ? e.altKey : false); break; case 'shift': m = (e.shiftKey ? e.shiftKey : false); break; } return m; } function getKey(e) { var k = false, c = (e.keyCode ? e.keyCode : e.which); // Handle keywords if (c == 13) k = 'enter'; // Handle letters else k = String.fromCharCode(c).toLowerCase(); return k; } function saveState() { createCookie(options.cookiePrefix + options.id, (sticky ? '1' : '0') + '-' + overlayZState + '-' + classNumber, 1); } function showOverlay() { overlay.show(); overlayVert.css({width: overlay.width()}); // hide any vertical blocks that aren't at the top of the viewport overlayVert.children('.vert').each(function () { var vCol = $(this); vCol.css('display','inline-block'); if (vCol.offset().top > vCol.parent().offset().top) { vCol.hide(); } }); } /** * Event handlers */ + var alreadyDown = {}; + function keydownHandler(e) { var k, m, source = e.target.tagName.toLowerCase(); if ((source == 'input') || (source == 'textarea') || (source == 'select')) { return true; } m = getModifier(e); if (!m) { return true; } k = getKey(e); if (!k) { return true; } + if (alreadyDown[k]) { + return; + } + alreadyDown[k] = true; + switch(k) { case options.showGridKey: if (!overlayOn) { showOverlay(); overlayOn = true; } else if (sticky) { overlay.hide(); overlayOn = false; sticky = false; saveState(); } break; case options.holdGridKey: if (overlayOn && !sticky) { // Turn sticky overlay on sticky = true; saveState(); } break; case options.foregroundKey: if (overlayOn) { // Toggle sticky overlay z-index if (overlay.css('z-index') == overlayZForeground) { overlay.css('z-index', overlayZBackground); overlayZState = 'B'; } else { overlay.css('z-index', overlayZForeground); overlayZState = 'F'; } saveState(); } break; case options.jumpGridsKey: if (overlayOn && (options.numberOfGrids > 1)) { // Cycle through the available grids overlay.removeClass(options.classPrefix + classNumber); classNumber++; if (classNumber > options.numberOfGrids) classNumber = 1; overlay.addClass(options.classPrefix + classNumber); showOverlay(); if (/webkit/.test( navigator.userAgent.toLowerCase() )) { forceRepaint(); } saveState(); } break; } return true; } function keyupHandler(e) { var k, m = getModifier(e); if (!m) { return true; } k = getKey(e); + alreadyDown[k] = false; if (k && (k == options.showGridKey) && !sticky) { overlay.hide(); overlayOn = false; } return true; } /** * Cookie functions * * By Peter-Paul Koch: * http://www.quirksmode.org/js/cookies.html */ function createCookie(name, value, days) { var date, expires = ""; if (days) { date = new Date(); date.setTime( date.getTime() + (days*24*60*60*1000) ); expires = "; expires=" + date.toGMTString(); } document.cookie = name + "=" + value + expires + "; path=/"; } function readCookie(name) { var c, ca = document.cookie.split(';'), i = 0, len = ca.length, nameEQ = name + "="; for (; i < len; i++) { c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1, c.length); } if (c.indexOf(nameEQ) == 0) { return c.substring(nameEQ.length, c.length); } } return null; } function eraseCookie(name) { createCookie(name, "", -1); } /** * Forces a repaint (because WebKit has issues) * http://www.sitepoint.com/forums/showthread.php?p=4538763 * http://www.phpied.com/the-new-game-show-will-it-reflow/ */ function forceRepaint() { var ss = document.styleSheets[0]; try { ss.addRule('.xxxxxx', 'position: relative'); ss.removeRule(ss.rules.length - 1); } catch(e) {} } return {}; }; /** * You can call hashgrid from your own code, but it's loaded here as * an example for your convenience. */ $(document).ready(function() { var grid = new hashgrid({ numberOfGrids: 2 }); });
dotjay/hashgrid
116a4d61cf5b158289bf22e1658bcc6ebb6561ce
Set valid cookies
diff --git a/hashgrid.js b/hashgrid.js index 09f7545..a583b8f 100644 --- a/hashgrid.js +++ b/hashgrid.js @@ -1,425 +1,425 @@ /** * hashgrid (jQuery version) * http://github.com/dotjay/hashgrid * Version 6, 10 Jun 2011 * Written by Jon Gibbins at Analog, http://analog.coop/ * * Contibutors: * Sean Coates, http://seancoates.com/ * Phil Dokas, http://jetless.org/ * Andrew Jaswa, http://andrewjaswa.com/ */ /** * @license Copyright 2011 Analog Coop Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Usage * * // The basic #grid setup looks like this * var grid = new hashgrid(); * * // Or you can set a custom id for your grid, e.g. #mygrid * var grid = new hashgrid("mygrid"); * * // But there are a whole bunch of additional options you can set * var grid = new hashgrid({ * id: 'mygrid', // id for the grid container * modifierKey: 'alt', // optional 'ctrl', 'alt' or 'shift' * showGridKey: 's', // key to show the grid * holdGridKey: 'enter', // key to hold the grid in place * foregroundKey: 'f', // key to toggle foreground/background * jumpGridsKey: 'd', // key to cycle through the grid classes * numberOfGrids: 2, // number of grid classes used * classPrefix: 'class', // prefix for the grid classes * cookiePrefix: 'mygrid' // prefix for the cookie name * }); */ /** * Make sure we have the library * TODO: Use an adapter */ if (typeof jQuery == "undefined") { alert("Hashgrid: jQuery not loaded. Make sure it's linked to your pages."); } /** * hashgrid overlay * @constructor */ var hashgrid = function(set) { var options = { id: 'grid', // id for the grid container modifierKey: null, // optional 'ctrl', 'alt' or 'shift' showGridKey: 'g', // key to show the grid holdGridKey: 'h', // key to hold the grid in place foregroundKey: 'f', // key to toggle foreground/background jumpGridsKey: 'j', // key to cycle through the grid classes numberOfGrids: 1, // number of grid classes used classPrefix: 'grid-', // prefix for the grid classes cookiePrefix: 'hashgrid'// prefix for the cookie name }, classNumber = 1, gridLines, gridWidth, i, line, lineHeight, numGridLines, overlay, overlayCookie, overlayEl, overlayOn = false, overlayVert, overlayZState = 'B', overlayZBackground = -1, overlayZForeground = 9999, pageHeight, setKey, state, sticky = false, top; // Apply options if (typeof set == 'object') { for (setKey in set) { options[setKey] = set[setKey]; } } else if (typeof set == 'string') { options.id = set; } // Remove any conflicting overlay if ($('#' + options.id).length > 0) { $('#' + options.id).remove(); } // Create overlay, hidden before adding to DOM overlayEl = $('<div></div>'); overlayEl .attr('id', options.id) .css({ display: 'none', 'pointer-events': 'none' }); $("body").prepend(overlayEl); overlay = $('#' + options.id); // Unless a custom z-index is set, ensure the overlay will be behind everything if (overlay.css('z-index') == 'auto') overlay.css('z-index', overlayZBackground); // Override the default overlay height with the actual page height pageHeight = parseFloat($(document).height()); overlay.height(pageHeight); // Add the first grid line so that we can measure it overlay.append('<div id="' + options.id + '-horiz" class="horiz first-line">'); // Position off-screen and display to calculate height top = overlay.css("top"); overlay.css({ top: "-999px", display: "block" }); // Calculate the number of grid lines needed line = $('#' + options.id + '-horiz'); lineHeight = line.outerHeight(); // Hide and reset top overlay.css({ display: "none", top: top }); // Break on zero line height if (lineHeight <= 0) { return false; } // Add the remaining grid lines numGridLines = Math.floor(pageHeight / lineHeight); gridLines = ''; for (i = numGridLines - 1; i >= 1; i--) { gridLines += '<div class="horiz"></div>'; } overlay.append(gridLines); // vertical grid overlay.append($('<div class="vert-container"></div>')); overlayVert = overlay.children('.vert-container'); gridWidth = overlay.width(); overlayVert.css({width: gridWidth, position: 'absolute', top: 0}); overlayVert.append('<div class="vert first-line">&nbsp;</div>'); // 30 is an arbitrarily large number... // can't calculate the margin width properly gridLines = ''; for (i = 0; i < 30; i++) { gridLines += '<div class="vert">&nbsp;</div>'; } overlayVert.append(gridLines); overlayVert.children() .height(pageHeight) .css({ display: 'inline-block' }); // Check for saved state overlayCookie = readCookie(options.cookiePrefix + options.id); if (typeof overlayCookie == 'string') { - state = overlayCookie.split(','); + state = overlayCookie.split('-'); state[2] = Number(state[2]); if ((typeof state[2] == 'number') && !isNaN(state[2])) { classNumber = state[2].toFixed(0); overlay.addClass(options.classPrefix + classNumber); } if (state[1] == 'F') { overlayZState = 'F'; overlay.css('z-index', overlayZForeground); } if (state[0] == '1') { overlayOn = true; sticky = true; showOverlay(); } } else { overlay.addClass(options.classPrefix + classNumber); } // Keyboard controls $(document).bind('keydown', keydownHandler); $(document).bind('keyup', keyupHandler); /** * Helpers */ function getModifier(e) { if (options.modifierKey == null) return true; // Bypass by default var m = true; switch(options.modifierKey) { case 'ctrl': m = (e.ctrlKey ? e.ctrlKey : false); break; case 'alt': m = (e.altKey ? e.altKey : false); break; case 'shift': m = (e.shiftKey ? e.shiftKey : false); break; } return m; } function getKey(e) { var k = false, c = (e.keyCode ? e.keyCode : e.which); // Handle keywords if (c == 13) k = 'enter'; // Handle letters else k = String.fromCharCode(c).toLowerCase(); return k; } function saveState() { - createCookie(options.cookiePrefix + options.id, (sticky ? '1' : '0') + ',' + overlayZState + ',' + classNumber, 1); + createCookie(options.cookiePrefix + options.id, (sticky ? '1' : '0') + '-' + overlayZState + '-' + classNumber, 1); } function showOverlay() { overlay.show(); overlayVert.css({width: overlay.width()}); // hide any vertical blocks that aren't at the top of the viewport overlayVert.children('.vert').each(function () { $(this).css('display','inline-block'); if ($(this).offset().top > 0) { $(this).hide(); } }); } /** * Event handlers */ function keydownHandler(e) { var k, m, source = e.target.tagName.toLowerCase(); if ((source == 'input') || (source == 'textarea') || (source == 'select')) { return true; } m = getModifier(e); if (!m) { return true; } k = getKey(e); if (!k) { return true; } switch(k) { case options.showGridKey: if (!overlayOn) { showOverlay(); overlayOn = true; } else if (sticky) { overlay.hide(); overlayOn = false; sticky = false; saveState(); } break; case options.holdGridKey: if (overlayOn && !sticky) { // Turn sticky overlay on sticky = true; saveState(); } break; case options.foregroundKey: if (overlayOn) { // Toggle sticky overlay z-index if (overlay.css('z-index') == overlayZForeground) { overlay.css('z-index', overlayZBackground); overlayZState = 'B'; } else { overlay.css('z-index', overlayZForeground); overlayZState = 'F'; } saveState(); } break; case options.jumpGridsKey: if (overlayOn && (options.numberOfGrids > 1)) { // Cycle through the available grids overlay.removeClass(options.classPrefix + classNumber); classNumber++; if (classNumber > options.numberOfGrids) classNumber = 1; overlay.addClass(options.classPrefix + classNumber); showOverlay(); if (/webkit/.test( navigator.userAgent.toLowerCase() )) { forceRepaint(); } saveState(); } break; } return true; } function keyupHandler(e) { var k, m = getModifier(e); if (!m) { return true; } k = getKey(e); if (k && (k == options.showGridKey) && !sticky) { overlay.hide(); overlayOn = false; } return true; } /** * Cookie functions * * By Peter-Paul Koch: * http://www.quirksmode.org/js/cookies.html */ function createCookie(name, value, days) { var date, expires = ""; if (days) { date = new Date(); date.setTime( date.getTime() + (days*24*60*60*1000) ); expires = "; expires=" + date.toGMTString(); } document.cookie = name + "=" + value + expires + "; path=/"; } function readCookie(name) { var c, ca = document.cookie.split(';'), i = 0, len = ca.length, nameEQ = name + "="; for (; i < len; i++) { c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1, c.length); } if (c.indexOf(nameEQ) == 0) { return c.substring(nameEQ.length, c.length); } } return null; } function eraseCookie(name) { createCookie(name, "", -1); } /** * Forces a repaint (because WebKit has issues) * http://www.sitepoint.com/forums/showthread.php?p=4538763 * http://www.phpied.com/the-new-game-show-will-it-reflow/ */ function forceRepaint() { var ss = document.styleSheets[0]; try { ss.addRule('.xxxxxx', 'position: relative'); ss.removeRule(ss.rules.length - 1); } catch(e) {} } return {}; }; /** * You can call hashgrid from your own code, but it's loaded here as * an example for your convenience. */ $(document).ready(function() { var grid = new hashgrid({ numberOfGrids: 2 }); });
dotjay/hashgrid
1090448f53d4469dd099db0520523d284db2ba34
store in a var
diff --git a/hashgrid.js b/hashgrid.js index 7d1992e..f2cde8b 100644 --- a/hashgrid.js +++ b/hashgrid.js @@ -1,425 +1,426 @@ /** * hashgrid (jQuery version) * http://github.com/dotjay/hashgrid * Version 6, 10 Jun 2011 * Written by Jon Gibbins at Analog, http://analog.coop/ * * Contibutors: * Sean Coates, http://seancoates.com/ * Phil Dokas, http://jetless.org/ * Andrew Jaswa, http://andrewjaswa.com/ */ /** * @license Copyright 2011 Analog Coop Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Usage * * // The basic #grid setup looks like this * var grid = new hashgrid(); * * // Or you can set a custom id for your grid, e.g. #mygrid * var grid = new hashgrid("mygrid"); * * // But there are a whole bunch of additional options you can set * var grid = new hashgrid({ * id: 'mygrid', // id for the grid container * modifierKey: 'alt', // optional 'ctrl', 'alt' or 'shift' * showGridKey: 's', // key to show the grid * holdGridKey: 'enter', // key to hold the grid in place * foregroundKey: 'f', // key to toggle foreground/background * jumpGridsKey: 'd', // key to cycle through the grid classes * numberOfGrids: 2, // number of grid classes used * classPrefix: 'class', // prefix for the grid classes * cookiePrefix: 'mygrid' // prefix for the cookie name * }); */ /** * Make sure we have the library * TODO: Use an adapter */ if (typeof jQuery == "undefined") { alert("Hashgrid: jQuery not loaded. Make sure it's linked to your pages."); } /** * hashgrid overlay * @constructor */ var hashgrid = function(set) { var options = { id: 'grid', // id for the grid container modifierKey: null, // optional 'ctrl', 'alt' or 'shift' showGridKey: 'g', // key to show the grid holdGridKey: 'h', // key to hold the grid in place foregroundKey: 'f', // key to toggle foreground/background jumpGridsKey: 'j', // key to cycle through the grid classes numberOfGrids: 1, // number of grid classes used classPrefix: 'grid-', // prefix for the grid classes cookiePrefix: 'hashgrid'// prefix for the cookie name }, classNumber = 1, gridLines, gridWidth, i, line, lineHeight, numGridLines, overlay, overlayCookie, overlayEl, overlayOn = false, overlayVert, overlayZState = 'B', overlayZBackground = -1, overlayZForeground = 9999, pageHeight, setKey, state, sticky = false, top; // Apply options if (typeof set == 'object') { for (setKey in set) { options[setKey] = set[setKey]; } } else if (typeof set == 'string') { options.id = set; } // Remove any conflicting overlay if ($('#' + options.id).length > 0) { $('#' + options.id).remove(); } // Create overlay, hidden before adding to DOM overlayEl = $('<div></div>'); overlayEl .attr('id', options.id) .css({ display: 'none', 'pointer-events': 'none' }); $("body").prepend(overlayEl); overlay = $('#' + options.id); // Unless a custom z-index is set, ensure the overlay will be behind everything if (overlay.css('z-index') == 'auto') overlay.css('z-index', overlayZBackground); // Override the default overlay height with the actual page height pageHeight = parseFloat($(document).height()); overlay.height(pageHeight); // Add the first grid line so that we can measure it overlay.append('<div id="' + options.id + '-horiz" class="horiz first-line">'); // Position off-screen and display to calculate height top = overlay.css("top"); overlay.css({ top: "-999px", display: "block" }); // Calculate the number of grid lines needed line = $('#' + options.id + '-horiz'); lineHeight = line.outerHeight(); // Hide and reset top overlay.css({ display: "none", top: top }); // Break on zero line height if (lineHeight <= 0) { return false; } // Add the remaining grid lines numGridLines = Math.floor(pageHeight / lineHeight); gridLines = ''; for (i = numGridLines - 1; i >= 1; i--) { gridLines += '<div class="horiz"></div>'; } overlay.append(gridLines); // vertical grid overlay.append($('<div class="vert-container"></div>')); overlayVert = overlay.children('.vert-container'); gridWidth = overlay.width(); overlayVert.css({width: gridWidth, position: 'absolute', top: 0}); overlayVert.append('<div class="vert first-line">&nbsp;</div>'); // 30 is an arbitrarily large number... // can't calculate the margin width properly gridLines = ''; for (i = 0; i < 30; i++) { gridLines += '<div class="vert">&nbsp;</div>'; } overlayVert.append(gridLines); overlayVert.children() .height(pageHeight) .css({ display: 'inline-block' }); // Check for saved state overlayCookie = readCookie(options.cookiePrefix + options.id); if (typeof overlayCookie == 'string') { state = overlayCookie.split(','); state[2] = Number(state[2]); if ((typeof state[2] == 'number') && !isNaN(state[2])) { classNumber = state[2].toFixed(0); overlay.addClass(options.classPrefix + classNumber); } if (state[1] == 'F') { overlayZState = 'F'; overlay.css('z-index', overlayZForeground); } if (state[0] == '1') { overlayOn = true; sticky = true; showOverlay(); } } else { overlay.addClass(options.classPrefix + classNumber); } // Keyboard controls $(document).bind('keydown', keydownHandler); $(document).bind('keyup', keyupHandler); /** * Helpers */ function getModifier(e) { if (options.modifierKey == null) return true; // Bypass by default var m = true; switch(options.modifierKey) { case 'ctrl': m = (e.ctrlKey ? e.ctrlKey : false); break; case 'alt': m = (e.altKey ? e.altKey : false); break; case 'shift': m = (e.shiftKey ? e.shiftKey : false); break; } return m; } function getKey(e) { var k = false, c = (e.keyCode ? e.keyCode : e.which); // Handle keywords if (c == 13) k = 'enter'; // Handle letters else k = String.fromCharCode(c).toLowerCase(); return k; } function saveState() { createCookie(options.cookiePrefix + options.id, (sticky ? '1' : '0') + ',' + overlayZState + ',' + classNumber, 1); } function showOverlay() { overlay.show(); overlayVert.css({width: overlay.width()}); // hide any vertical blocks that aren't at the top of the viewport overlayVert.children('.vert').each(function () { - $(this).css('display','inline-block'); - if ($(this).offset().top > $(this).parent().offset().top) { - $(this).hide(); + var vCol = $(this); + vCol.css('display','inline-block'); + if (vCol.offset().top > vCol.parent().offset().top) { + vCol.hide(); } }); } /** * Event handlers */ function keydownHandler(e) { var k, m, source = e.target.tagName.toLowerCase(); if ((source == 'input') || (source == 'textarea') || (source == 'select')) { return true; } m = getModifier(e); if (!m) { return true; } k = getKey(e); if (!k) { return true; } switch(k) { case options.showGridKey: if (!overlayOn) { showOverlay(); overlayOn = true; } else if (sticky) { overlay.hide(); overlayOn = false; sticky = false; saveState(); } break; case options.holdGridKey: if (overlayOn && !sticky) { // Turn sticky overlay on sticky = true; saveState(); } break; case options.foregroundKey: if (overlayOn) { // Toggle sticky overlay z-index if (overlay.css('z-index') == overlayZForeground) { overlay.css('z-index', overlayZBackground); overlayZState = 'B'; } else { overlay.css('z-index', overlayZForeground); overlayZState = 'F'; } saveState(); } break; case options.jumpGridsKey: if (overlayOn && (options.numberOfGrids > 1)) { // Cycle through the available grids overlay.removeClass(options.classPrefix + classNumber); classNumber++; if (classNumber > options.numberOfGrids) classNumber = 1; overlay.addClass(options.classPrefix + classNumber); showOverlay(); if (/webkit/.test( navigator.userAgent.toLowerCase() )) { forceRepaint(); } saveState(); } break; } return true; } function keyupHandler(e) { var k, m = getModifier(e); if (!m) { return true; } k = getKey(e); if (k && (k == options.showGridKey) && !sticky) { overlay.hide(); overlayOn = false; } return true; } /** * Cookie functions * * By Peter-Paul Koch: * http://www.quirksmode.org/js/cookies.html */ function createCookie(name, value, days) { var date, expires = ""; if (days) { date = new Date(); date.setTime( date.getTime() + (days*24*60*60*1000) ); expires = "; expires=" + date.toGMTString(); } document.cookie = name + "=" + value + expires + "; path=/"; } function readCookie(name) { var c, ca = document.cookie.split(';'), i = 0, len = ca.length, nameEQ = name + "="; for (; i < len; i++) { c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1, c.length); } if (c.indexOf(nameEQ) == 0) { return c.substring(nameEQ.length, c.length); } } return null; } function eraseCookie(name) { createCookie(name, "", -1); } /** * Forces a repaint (because WebKit has issues) * http://www.sitepoint.com/forums/showthread.php?p=4538763 * http://www.phpied.com/the-new-game-show-will-it-reflow/ */ function forceRepaint() { var ss = document.styleSheets[0]; try { ss.addRule('.xxxxxx', 'position: relative'); ss.removeRule(ss.rules.length - 1); } catch(e) {} } return {}; }; /** * You can call hashgrid from your own code, but it's loaded here as * an example for your convenience. */ $(document).ready(function() { var grid = new hashgrid({ numberOfGrids: 2 }); });
dotjay/hashgrid
ea337a59e082e6025ae78483a8a19b350cfcb9a2
Fix showOverlay() to work when used inside a wrapping container with position:relative instead of the whole viewport.
diff --git a/hashgrid.js b/hashgrid.js index 09f7545..7d1992e 100644 --- a/hashgrid.js +++ b/hashgrid.js @@ -1,425 +1,425 @@ /** * hashgrid (jQuery version) * http://github.com/dotjay/hashgrid * Version 6, 10 Jun 2011 * Written by Jon Gibbins at Analog, http://analog.coop/ * * Contibutors: * Sean Coates, http://seancoates.com/ * Phil Dokas, http://jetless.org/ * Andrew Jaswa, http://andrewjaswa.com/ */ /** * @license Copyright 2011 Analog Coop Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Usage * * // The basic #grid setup looks like this * var grid = new hashgrid(); * * // Or you can set a custom id for your grid, e.g. #mygrid * var grid = new hashgrid("mygrid"); * * // But there are a whole bunch of additional options you can set * var grid = new hashgrid({ * id: 'mygrid', // id for the grid container * modifierKey: 'alt', // optional 'ctrl', 'alt' or 'shift' * showGridKey: 's', // key to show the grid * holdGridKey: 'enter', // key to hold the grid in place * foregroundKey: 'f', // key to toggle foreground/background * jumpGridsKey: 'd', // key to cycle through the grid classes * numberOfGrids: 2, // number of grid classes used * classPrefix: 'class', // prefix for the grid classes * cookiePrefix: 'mygrid' // prefix for the cookie name * }); */ /** * Make sure we have the library * TODO: Use an adapter */ if (typeof jQuery == "undefined") { alert("Hashgrid: jQuery not loaded. Make sure it's linked to your pages."); } /** * hashgrid overlay * @constructor */ var hashgrid = function(set) { var options = { id: 'grid', // id for the grid container modifierKey: null, // optional 'ctrl', 'alt' or 'shift' showGridKey: 'g', // key to show the grid holdGridKey: 'h', // key to hold the grid in place foregroundKey: 'f', // key to toggle foreground/background jumpGridsKey: 'j', // key to cycle through the grid classes numberOfGrids: 1, // number of grid classes used classPrefix: 'grid-', // prefix for the grid classes cookiePrefix: 'hashgrid'// prefix for the cookie name }, classNumber = 1, gridLines, gridWidth, i, line, lineHeight, numGridLines, overlay, overlayCookie, overlayEl, overlayOn = false, overlayVert, overlayZState = 'B', overlayZBackground = -1, overlayZForeground = 9999, pageHeight, setKey, state, sticky = false, top; // Apply options if (typeof set == 'object') { for (setKey in set) { options[setKey] = set[setKey]; } } else if (typeof set == 'string') { options.id = set; } // Remove any conflicting overlay if ($('#' + options.id).length > 0) { $('#' + options.id).remove(); } // Create overlay, hidden before adding to DOM overlayEl = $('<div></div>'); overlayEl .attr('id', options.id) .css({ display: 'none', 'pointer-events': 'none' }); $("body").prepend(overlayEl); overlay = $('#' + options.id); // Unless a custom z-index is set, ensure the overlay will be behind everything if (overlay.css('z-index') == 'auto') overlay.css('z-index', overlayZBackground); // Override the default overlay height with the actual page height pageHeight = parseFloat($(document).height()); overlay.height(pageHeight); // Add the first grid line so that we can measure it overlay.append('<div id="' + options.id + '-horiz" class="horiz first-line">'); // Position off-screen and display to calculate height top = overlay.css("top"); overlay.css({ top: "-999px", display: "block" }); // Calculate the number of grid lines needed line = $('#' + options.id + '-horiz'); lineHeight = line.outerHeight(); // Hide and reset top overlay.css({ display: "none", top: top }); // Break on zero line height if (lineHeight <= 0) { return false; } // Add the remaining grid lines numGridLines = Math.floor(pageHeight / lineHeight); gridLines = ''; for (i = numGridLines - 1; i >= 1; i--) { gridLines += '<div class="horiz"></div>'; } overlay.append(gridLines); // vertical grid overlay.append($('<div class="vert-container"></div>')); overlayVert = overlay.children('.vert-container'); gridWidth = overlay.width(); overlayVert.css({width: gridWidth, position: 'absolute', top: 0}); overlayVert.append('<div class="vert first-line">&nbsp;</div>'); // 30 is an arbitrarily large number... // can't calculate the margin width properly gridLines = ''; for (i = 0; i < 30; i++) { gridLines += '<div class="vert">&nbsp;</div>'; } overlayVert.append(gridLines); overlayVert.children() .height(pageHeight) .css({ display: 'inline-block' }); // Check for saved state overlayCookie = readCookie(options.cookiePrefix + options.id); if (typeof overlayCookie == 'string') { state = overlayCookie.split(','); state[2] = Number(state[2]); if ((typeof state[2] == 'number') && !isNaN(state[2])) { classNumber = state[2].toFixed(0); overlay.addClass(options.classPrefix + classNumber); } if (state[1] == 'F') { overlayZState = 'F'; overlay.css('z-index', overlayZForeground); } if (state[0] == '1') { overlayOn = true; sticky = true; showOverlay(); } } else { overlay.addClass(options.classPrefix + classNumber); } // Keyboard controls $(document).bind('keydown', keydownHandler); $(document).bind('keyup', keyupHandler); /** * Helpers */ function getModifier(e) { if (options.modifierKey == null) return true; // Bypass by default var m = true; switch(options.modifierKey) { case 'ctrl': m = (e.ctrlKey ? e.ctrlKey : false); break; case 'alt': m = (e.altKey ? e.altKey : false); break; case 'shift': m = (e.shiftKey ? e.shiftKey : false); break; } return m; } function getKey(e) { var k = false, c = (e.keyCode ? e.keyCode : e.which); // Handle keywords if (c == 13) k = 'enter'; // Handle letters else k = String.fromCharCode(c).toLowerCase(); return k; } function saveState() { createCookie(options.cookiePrefix + options.id, (sticky ? '1' : '0') + ',' + overlayZState + ',' + classNumber, 1); } function showOverlay() { overlay.show(); overlayVert.css({width: overlay.width()}); // hide any vertical blocks that aren't at the top of the viewport overlayVert.children('.vert').each(function () { $(this).css('display','inline-block'); - if ($(this).offset().top > 0) { + if ($(this).offset().top > $(this).parent().offset().top) { $(this).hide(); } }); } /** * Event handlers */ function keydownHandler(e) { var k, m, source = e.target.tagName.toLowerCase(); if ((source == 'input') || (source == 'textarea') || (source == 'select')) { return true; } m = getModifier(e); if (!m) { return true; } k = getKey(e); if (!k) { return true; } switch(k) { case options.showGridKey: if (!overlayOn) { showOverlay(); overlayOn = true; } else if (sticky) { overlay.hide(); overlayOn = false; sticky = false; saveState(); } break; case options.holdGridKey: if (overlayOn && !sticky) { // Turn sticky overlay on sticky = true; saveState(); } break; case options.foregroundKey: if (overlayOn) { // Toggle sticky overlay z-index if (overlay.css('z-index') == overlayZForeground) { overlay.css('z-index', overlayZBackground); overlayZState = 'B'; } else { overlay.css('z-index', overlayZForeground); overlayZState = 'F'; } saveState(); } break; case options.jumpGridsKey: if (overlayOn && (options.numberOfGrids > 1)) { // Cycle through the available grids overlay.removeClass(options.classPrefix + classNumber); classNumber++; if (classNumber > options.numberOfGrids) classNumber = 1; overlay.addClass(options.classPrefix + classNumber); showOverlay(); if (/webkit/.test( navigator.userAgent.toLowerCase() )) { forceRepaint(); } saveState(); } break; } return true; } function keyupHandler(e) { var k, m = getModifier(e); if (!m) { return true; } k = getKey(e); if (k && (k == options.showGridKey) && !sticky) { overlay.hide(); overlayOn = false; } return true; } /** * Cookie functions * * By Peter-Paul Koch: * http://www.quirksmode.org/js/cookies.html */ function createCookie(name, value, days) { var date, expires = ""; if (days) { date = new Date(); date.setTime( date.getTime() + (days*24*60*60*1000) ); expires = "; expires=" + date.toGMTString(); } document.cookie = name + "=" + value + expires + "; path=/"; } function readCookie(name) { var c, ca = document.cookie.split(';'), i = 0, len = ca.length, nameEQ = name + "="; for (; i < len; i++) { c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1, c.length); } if (c.indexOf(nameEQ) == 0) { return c.substring(nameEQ.length, c.length); } } return null; } function eraseCookie(name) { createCookie(name, "", -1); } /** * Forces a repaint (because WebKit has issues) * http://www.sitepoint.com/forums/showthread.php?p=4538763 * http://www.phpied.com/the-new-game-show-will-it-reflow/ */ function forceRepaint() { var ss = document.styleSheets[0]; try { ss.addRule('.xxxxxx', 'position: relative'); ss.removeRule(ss.rules.length - 1); } catch(e) {} } return {}; }; /** * You can call hashgrid from your own code, but it's loaded here as * an example for your convenience. */ $(document).ready(function() { var grid = new hashgrid({ numberOfGrids: 2 }); });
dotjay/hashgrid
30205bdd28c052759c228896abb9e1c7595bd48c
Release v7
diff --git a/index.htm b/index.htm index 9cbce20..596c5fb 100644 --- a/index.htm +++ b/index.htm @@ -1,444 +1,446 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>#grid</title> <style type="text/css"> /* Putting inline rules here so the document can be downloaded with style */ body{ font-size: 1em; line-height: 1.25; font-family: Arial, sans-serif; background: White; color: DimGray; margin: 0; padding: 0 20px; } #content{ font-size: 16px; line-height: 20px; position: relative; } #content{ width: 620px; margin: 0 auto; } #footer{ border-top: 1px dotted DarkGray; padding-top: 19px; } h1, h2{ color: Black; font-weight: normal; } h1{ font-size: 36px; line-height: 40px; margin: 40px 0 20px; padding-bottom: 19px; border-bottom: 1px dotted DarkGray; } h1 em{ font-style: normal; color: DarkGray; font-size: 16px; line-height: 20px; margin: 0 0 20px; } h2, h3{ font-size: 16px; font-weight: 700; line-height: 20px; margin: 0 0 20px; } h3{ font-weight: 300; } a:link, a:visited{ color: Black; text-decoration: none; padding: 0 2px; background-color: WhiteSmoke; border-bottom: 1px solid Gold; } a:focus{ outline: none; } a:focus, a:hover, a:active{ background-color: Khaki; border-bottom: 1px solid GoldenRod; } p, ul{ padding: 0; margin: 0 0 20px; } dl, ol{ padding: 0; margin: 0; } ul{ list-style: circle; } ol li{ margin-bottom: 20px; } dd{ margin: 0 0 20px 0; } del{ text-decoration: line-through; opacity: 0.75; } ins{ text-decoration: none; } code{ font-size: 14px; line-height: 1; } textarea{ font-family: 'Courier New', monospace; font-size: 14px; line-height: 20px; display: block; width: 600px; margin: 0 0 20px; padding: 0 0 0 15px; border: 0; color: Black; background: Gainsboro; border-left: 5px solid DarkGray; } #javascript-code{ height: 180px; } #css-code{ height: 1300px; } .summary em{ font-style: normal; position: absolute; color: DarkGray; right: 0; top: 18px; width: 140px; } .summary em span{ position: absolute; left: -9999px; } #download{ line-height: 60px; padding: 0 40px 0 15px; border-left: 5px solid DarkGray; background: Gainsboro; color: DimGray; } span.key{ color: Black; text-transform: uppercase; } </style> <!-- Set styles --> <style type="text/css"> /** * Grid */ #grid{ /* Dimensions - same width as your grid with gutters */ width: 980px; /* Grid (left-aligned) position: absolute; top: 0; left: 0; */ /* Grid (centered) */ position: absolute; top: 0; left: 50%; margin-left: -490px; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ #grid div.vert{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-right: 19px; } #grid div.vert.first-line{ margin-left: 19px; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ #grid div.horiz{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option in the hashgrid.js file. */ #grid.grid-1 div.vert{ /* Vertical grid line colour for grid 1 */ border-color: darkturquoise; } #grid.grid-2{ /* Adjustments */ padding: 0 160px; width: 660px; } #grid.grid-2 div.vert{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </style> </head> <body> <div id="content" role="main"> -<h1>#grid <em>v6</em></h1> +<h1>#grid <em>v7</em></h1> -<p class="summary"><em>Fri, 10 Jun 2011<span>:</span></em> This is a little tool we created for our <a href="http://analog.coop/">Analog&#160;holding&#160;page</a>. It inserts a <a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a> in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit <span class="key">G</span> on your keyboard.</p> +<p class="summary"><em>Sat, 11 Jun 2011<span>:</span></em> This is a little tool we created for our <a href="http://analog.coop/">Analog&#160;holding&#160;page</a>. It inserts a <a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a> in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit <span class="key">G</span> on your keyboard.</p> <h2>Download</h2> <p id="download"><a href="http://github.com/dotjay/hashgrid/downloads">Download #grid</a> from <a href="http://github.com/dotjay/hashgrid">GitHub</a></p> <h2 id="features">Features</h2> <ul> <li>Adaptable for all layout widths and alignments</li> <li>Adaptable for any vertical rhythm value</li> <li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li> <li>Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters</li> </ul> <p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p> <h2 id="installation">Installation</h2> <ol> -<li><h3>Copy the <a href="http://github.com/dotjay/hashgrid/blob/v6/hashgrid.js">hashgrid.js</a> script to your project</h3></li> +<li><h3>Copy the <a href="http://github.com/dotjay/hashgrid/blob/v7/hashgrid.js">hashgrid.js</a> script to your project</h3></li> <li><h3>Add the script to your page(s) just inside the <code>&#60;/body&#62;</code> tag</h3> <textarea id="javascript-code" cols="68" rows="8" readonly="readonly"> &#60;!-- Grab latest version of jQuery --&#62; &#60;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"&#62; &#60;/script&#62; &#60;!-- Include the hashgrid script --&#62; &#60;script type="text/javascript" src="hashgrid.js"&#62;&#60;/script&#62;</textarea></li> <li><h3>Add the CSS to your page(s)</h3> <textarea id="css-code" cols="68" rows="64" readonly="readonly"> /** * Grid */ #grid{ /* Dimensions - same width as your grid with gutters */ width: 980px; /* Grid (left-aligned) position: absolute; top: 0; left: 0; */ /* Grid (centered) */ position: absolute; top: 0; left: 50%; margin-left: -490px; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ #grid div.vert{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-right: 19px; } #grid div.vert.first-line{ margin-left: 19px; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ #grid div.horiz{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option in the hashgrid.js file. */ #grid.grid-1 div.vert{ /* Vertical grid line colour for grid 1 */ border-color: darkturquoise; } #grid.grid-2{ /* Adjustments */ padding: 0 160px; width: 660px; } #grid.grid-2 div.vert{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </textarea></li> <li><h3>Modify #grid to suit your needs</h3> <p>The CSS and JavaScript is annotated to help you.</p></li> </ol> <h2 id="usage">Usage</h2> <p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p> <dl> <dt><span class="key">G</span></dt> <dd>Show the grid until you release.</dd> <dt><span class="key">G</span> + <span class="key">H</span></dt> <dd>Show and hold the grid (<span class="key">G</span> will remove it again).</dd> <dt><span class="key">G</span> + <span class="key">F</span></dt> <dd>Toggle the grid to the foreground and back. Pressing <span class="key">F</span> while the grid is held also works.</dd> <dt><span class="key">G</span> + <span class="key">J</span></dt> <dd>Jump to the next grid. Pressing <span class="key">J</span> while the grid is held also works.</dd> </dl> <p><em>N.B. A cookie conveniently remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page except in Chrome v4, Safari v4, Firefox v3.6, or more recent versions.</em></p> <h2 id="release-notes">Release Notes</h2> <dl> +<dt>v7&#8201;&#8212;&#8201;11 Jun 2011</dt> +<dd>Minor release: Updated license references.</dd> <dt>v6&#8201;&#8212;&#8201;10 Jun 2011</dt> -<dd>Minor release for optimisations, and now released under an Apache License.</dd> +<dd>Minor release: Optimisations, and now released under an Apache License.</dd> <dt>v5&#8201;&#8212;&#8201;3 Nov 2010</dt> <dd> <ul> <li>Vertical grid lines can now be set using CSS&#8230; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution.</li> <li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li> <li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback.</li> </ul> </dd> <dt>v4&#8201;&#8212;&#8201;29 Mar 2010</dt> <dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd> <dt>v3&#8201;&#8212;&#8201;22 Feb 2010</dt> <dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd> <dt>v2&#8201;&#8212;&#8201;2 Feb 2010</dt> <dd>Keys are now more easily configured (see top of hashgrid.js). Renamed the GridOverlay object to hashgrid. Fixed crash when using with disabled CSS.</dd> <dt>v1&#8201;&#8212;&#8201;21 Dec 2009</dt> <dd>First release.</dd> </dl> <h2 id="known-issues">Known Issues</h2> <ul> <li><del>IE 8: Fully functional, but the default <span class="key">ALT</span> + <span class="key">G</span> + <span class="key">ENTER</span> shortcut puts IE into full screen mode. Hit <span class="key">ALT</span> + <span class="key">ENTER</span> to toggle full screen mode off again.</del><ins datetime="2010-02-22"> The default keyboard shortcuts have been changed.</ins></li> <li>IE 6: The grid is always in the foreground.</li> <li>Opera 9/10: Using <span class="key">CTRL</span> or <span class="key">ALT</span> as a modifier key will not work due to different key handling by the browser.</li> </ul> <h2 id="license">License</h2> <p>Copyright 2011 Analog Coop Limited</p> <p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br /><br /> <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a></p> <p>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.</p> <p>This essentially means that you&#8217;re free to copy, modify and distribute it for any project so long as you provide clear attribution to Analog Coop Limited. <a href="http://analog.coop/#talk-to-us">Contact us</a> if you need a different license.</p> <div id="footer" role="contentinfo"> <p>#grid is an <a href="http://analog.coop/">Analog</a> gig. It was conceived by <a href="http://jontangerine.com/">Jon Tan</a>, and built by <a href="http://accessibility.co.uk/">Jon Gibbins</a>, in cahoots with our <a href="http://analog.coop#is">fine friends</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p> </div> </div> <!-- Grab latest version of jQuery --> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script> <!-- Include the hashgrid script --> <script type="text/javascript" src="hashgrid.js"></script> </body> </html>
dotjay/hashgrid
e072a394839c9500f27771bd81c390c459f675c5
Add LICENSE file to distribution
diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..a31baaa --- /dev/null +++ b/LICENSE @@ -0,0 +1,13 @@ +Copyright 2011 Analog Coop Limited + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License.
dotjay/hashgrid
c95f45794316bed3661ba4407c5deddff302b6ff
Use Apache License boilerplate.
diff --git a/README.md b/README.md index 399338c..b1d20a0 100644 --- a/README.md +++ b/README.md @@ -1,20 +1,35 @@ # #grid # A little tool that inserts a layout grid in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. ## Features ## * Adaptable for all layout widths and alignments * Adaptable for any vertical rhythm value * Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids * Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters Notes on installation and usage can be found in the included index.htm file. ## License ## -Released under an Apache License (Version 2.0), which essentially means that you're free to copy, modify and distribute it for any project so long as you provide clear attribution to Analog. -http://www.apache.org/licenses/LICENSE-2.0.html +Copyright 2011 Analog Coop Limited + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +-- + +This essentially means that you're free to copy, modify and distribute it for any project so long as you provide clear attribution to Analog Coop Limited. Contact us if you need a different license. http://analog.coop/ diff --git a/hashgrid.js b/hashgrid.js index 420e6a0..09f7545 100644 --- a/hashgrid.js +++ b/hashgrid.js @@ -1,401 +1,425 @@ /** * hashgrid (jQuery version) * http://github.com/dotjay/hashgrid * Version 6, 10 Jun 2011 * Written by Jon Gibbins at Analog, http://analog.coop/ * * Contibutors: * Sean Coates, http://seancoates.com/ * Phil Dokas, http://jetless.org/ * Andrew Jaswa, http://andrewjaswa.com/ + */ + +/** + * @license Copyright 2011 Analog Coop Limited * - * License: - * http://www.apache.org/licenses/LICENSE-2.0.html + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Usage * - * // Using a basic #grid setup + * // The basic #grid setup looks like this * var grid = new hashgrid(); * - * // Using #grid with a custom id (e.g. #mygrid) + * // Or you can set a custom id for your grid, e.g. #mygrid * var grid = new hashgrid("mygrid"); * - * // Using #grid with additional options + * // But there are a whole bunch of additional options you can set * var grid = new hashgrid({ * id: 'mygrid', // id for the grid container * modifierKey: 'alt', // optional 'ctrl', 'alt' or 'shift' * showGridKey: 's', // key to show the grid * holdGridKey: 'enter', // key to hold the grid in place * foregroundKey: 'f', // key to toggle foreground/background * jumpGridsKey: 'd', // key to cycle through the grid classes * numberOfGrids: 2, // number of grid classes used * classPrefix: 'class', // prefix for the grid classes * cookiePrefix: 'mygrid' // prefix for the cookie name * }); */ + + +/** + * Make sure we have the library + * TODO: Use an adapter + */ if (typeof jQuery == "undefined") { alert("Hashgrid: jQuery not loaded. Make sure it's linked to your pages."); } /** * hashgrid overlay + * @constructor */ var hashgrid = function(set) { var options = { id: 'grid', // id for the grid container modifierKey: null, // optional 'ctrl', 'alt' or 'shift' showGridKey: 'g', // key to show the grid holdGridKey: 'h', // key to hold the grid in place foregroundKey: 'f', // key to toggle foreground/background jumpGridsKey: 'j', // key to cycle through the grid classes numberOfGrids: 1, // number of grid classes used classPrefix: 'grid-', // prefix for the grid classes cookiePrefix: 'hashgrid'// prefix for the cookie name }, classNumber = 1, gridLines, gridWidth, i, line, lineHeight, numGridLines, overlay, overlayCookie, overlayEl, overlayOn = false, overlayVert, overlayZState = 'B', overlayZBackground = -1, overlayZForeground = 9999, pageHeight, setKey, state, sticky = false, top; // Apply options if (typeof set == 'object') { for (setKey in set) { options[setKey] = set[setKey]; } } else if (typeof set == 'string') { options.id = set; } // Remove any conflicting overlay if ($('#' + options.id).length > 0) { $('#' + options.id).remove(); } // Create overlay, hidden before adding to DOM overlayEl = $('<div></div>'); overlayEl .attr('id', options.id) .css({ display: 'none', 'pointer-events': 'none' }); $("body").prepend(overlayEl); overlay = $('#' + options.id); // Unless a custom z-index is set, ensure the overlay will be behind everything if (overlay.css('z-index') == 'auto') overlay.css('z-index', overlayZBackground); // Override the default overlay height with the actual page height pageHeight = parseFloat($(document).height()); overlay.height(pageHeight); // Add the first grid line so that we can measure it overlay.append('<div id="' + options.id + '-horiz" class="horiz first-line">'); // Position off-screen and display to calculate height top = overlay.css("top"); overlay.css({ top: "-999px", display: "block" }); // Calculate the number of grid lines needed line = $('#' + options.id + '-horiz'); lineHeight = line.outerHeight(); // Hide and reset top overlay.css({ display: "none", top: top }); // Break on zero line height if (lineHeight <= 0) { return false; } // Add the remaining grid lines numGridLines = Math.floor(pageHeight / lineHeight); gridLines = ''; for (i = numGridLines - 1; i >= 1; i--) { gridLines += '<div class="horiz"></div>'; } overlay.append(gridLines); // vertical grid overlay.append($('<div class="vert-container"></div>')); overlayVert = overlay.children('.vert-container'); gridWidth = overlay.width(); overlayVert.css({width: gridWidth, position: 'absolute', top: 0}); overlayVert.append('<div class="vert first-line">&nbsp;</div>'); // 30 is an arbitrarily large number... // can't calculate the margin width properly gridLines = ''; for (i = 0; i < 30; i++) { gridLines += '<div class="vert">&nbsp;</div>'; } overlayVert.append(gridLines); overlayVert.children() .height(pageHeight) .css({ display: 'inline-block' }); // Check for saved state overlayCookie = readCookie(options.cookiePrefix + options.id); if (typeof overlayCookie == 'string') { state = overlayCookie.split(','); state[2] = Number(state[2]); if ((typeof state[2] == 'number') && !isNaN(state[2])) { classNumber = state[2].toFixed(0); overlay.addClass(options.classPrefix + classNumber); } if (state[1] == 'F') { overlayZState = 'F'; overlay.css('z-index', overlayZForeground); } if (state[0] == '1') { overlayOn = true; sticky = true; showOverlay(); } } else { overlay.addClass(options.classPrefix + classNumber); } // Keyboard controls $(document).bind('keydown', keydownHandler); $(document).bind('keyup', keyupHandler); /** * Helpers */ function getModifier(e) { if (options.modifierKey == null) return true; // Bypass by default var m = true; switch(options.modifierKey) { case 'ctrl': m = (e.ctrlKey ? e.ctrlKey : false); break; case 'alt': m = (e.altKey ? e.altKey : false); break; case 'shift': m = (e.shiftKey ? e.shiftKey : false); break; } return m; } function getKey(e) { var k = false, c = (e.keyCode ? e.keyCode : e.which); // Handle keywords if (c == 13) k = 'enter'; // Handle letters else k = String.fromCharCode(c).toLowerCase(); return k; } function saveState() { createCookie(options.cookiePrefix + options.id, (sticky ? '1' : '0') + ',' + overlayZState + ',' + classNumber, 1); } function showOverlay() { overlay.show(); overlayVert.css({width: overlay.width()}); // hide any vertical blocks that aren't at the top of the viewport overlayVert.children('.vert').each(function () { $(this).css('display','inline-block'); if ($(this).offset().top > 0) { $(this).hide(); } }); } /** * Event handlers */ function keydownHandler(e) { var k, m, source = e.target.tagName.toLowerCase(); if ((source == 'input') || (source == 'textarea') || (source == 'select')) { return true; } m = getModifier(e); if (!m) { return true; } k = getKey(e); if (!k) { return true; } switch(k) { case options.showGridKey: if (!overlayOn) { showOverlay(); overlayOn = true; } else if (sticky) { overlay.hide(); overlayOn = false; sticky = false; saveState(); } break; case options.holdGridKey: if (overlayOn && !sticky) { // Turn sticky overlay on sticky = true; saveState(); } break; case options.foregroundKey: if (overlayOn) { // Toggle sticky overlay z-index if (overlay.css('z-index') == overlayZForeground) { overlay.css('z-index', overlayZBackground); overlayZState = 'B'; } else { overlay.css('z-index', overlayZForeground); overlayZState = 'F'; } saveState(); } break; case options.jumpGridsKey: if (overlayOn && (options.numberOfGrids > 1)) { // Cycle through the available grids overlay.removeClass(options.classPrefix + classNumber); classNumber++; if (classNumber > options.numberOfGrids) classNumber = 1; overlay.addClass(options.classPrefix + classNumber); showOverlay(); if (/webkit/.test( navigator.userAgent.toLowerCase() )) { forceRepaint(); } saveState(); } break; } return true; } function keyupHandler(e) { var k, m = getModifier(e); if (!m) { return true; } k = getKey(e); if (k && (k == options.showGridKey) && !sticky) { overlay.hide(); overlayOn = false; } return true; } /** * Cookie functions * * By Peter-Paul Koch: * http://www.quirksmode.org/js/cookies.html */ function createCookie(name, value, days) { var date, expires = ""; if (days) { date = new Date(); date.setTime( date.getTime() + (days*24*60*60*1000) ); expires = "; expires=" + date.toGMTString(); } document.cookie = name + "=" + value + expires + "; path=/"; } function readCookie(name) { var c, ca = document.cookie.split(';'), i = 0, len = ca.length, nameEQ = name + "="; for (; i < len; i++) { c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1, c.length); } if (c.indexOf(nameEQ) == 0) { return c.substring(nameEQ.length, c.length); } } return null; } function eraseCookie(name) { createCookie(name, "", -1); } /** * Forces a repaint (because WebKit has issues) * http://www.sitepoint.com/forums/showthread.php?p=4538763 * http://www.phpied.com/the-new-game-show-will-it-reflow/ */ function forceRepaint() { var ss = document.styleSheets[0]; try { ss.addRule('.xxxxxx', 'position: relative'); ss.removeRule(ss.rules.length - 1); } catch(e) {} } return {}; }; /** * You can call hashgrid from your own code, but it's loaded here as * an example for your convenience. */ $(document).ready(function() { var grid = new hashgrid({ numberOfGrids: 2 }); }); diff --git a/index.htm b/index.htm index b9d74b6..9cbce20 100644 --- a/index.htm +++ b/index.htm @@ -1,429 +1,444 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>#grid</title> <style type="text/css"> /* Putting inline rules here so the document can be downloaded with style */ body{ font-size: 1em; line-height: 1.25; font-family: Arial, sans-serif; background: White; color: DimGray; margin: 0; padding: 0 20px; } #content{ font-size: 16px; line-height: 20px; position: relative; } #content{ width: 620px; margin: 0 auto; } #footer{ border-top: 1px dotted DarkGray; padding-top: 19px; } h1, h2{ color: Black; font-weight: normal; } h1{ font-size: 36px; line-height: 40px; margin: 40px 0 20px; padding-bottom: 19px; border-bottom: 1px dotted DarkGray; } h1 em{ font-style: normal; color: DarkGray; font-size: 16px; line-height: 20px; margin: 0 0 20px; } h2, h3{ font-size: 16px; font-weight: 700; line-height: 20px; margin: 0 0 20px; } h3{ font-weight: 300; } a:link, a:visited{ color: Black; text-decoration: none; padding: 0 2px; background-color: WhiteSmoke; border-bottom: 1px solid Gold; } a:focus{ outline: none; } a:focus, a:hover, a:active{ background-color: Khaki; border-bottom: 1px solid GoldenRod; } p, ul{ padding: 0; margin: 0 0 20px; } dl, ol{ padding: 0; margin: 0; } ul{ list-style: circle; } ol li{ margin-bottom: 20px; } dd{ margin: 0 0 20px 0; } del{ text-decoration: line-through; opacity: 0.75; } ins{ text-decoration: none; } code{ font-size: 14px; line-height: 1; } textarea{ font-family: 'Courier New', monospace; font-size: 14px; line-height: 20px; display: block; width: 600px; margin: 0 0 20px; padding: 0 0 0 15px; border: 0; color: Black; background: Gainsboro; border-left: 5px solid DarkGray; } #javascript-code{ height: 180px; } #css-code{ height: 1300px; } .summary em{ font-style: normal; position: absolute; color: DarkGray; right: 0; top: 18px; width: 140px; } .summary em span{ position: absolute; left: -9999px; } #download{ line-height: 60px; padding: 0 40px 0 15px; border-left: 5px solid DarkGray; background: Gainsboro; color: DimGray; } span.key{ color: Black; text-transform: uppercase; } </style> <!-- Set styles --> <style type="text/css"> /** * Grid */ #grid{ /* Dimensions - same width as your grid with gutters */ width: 980px; /* Grid (left-aligned) position: absolute; top: 0; left: 0; */ /* Grid (centered) */ position: absolute; top: 0; left: 50%; margin-left: -490px; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ #grid div.vert{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-right: 19px; } #grid div.vert.first-line{ margin-left: 19px; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ #grid div.horiz{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option in the hashgrid.js file. */ #grid.grid-1 div.vert{ /* Vertical grid line colour for grid 1 */ border-color: darkturquoise; } #grid.grid-2{ /* Adjustments */ padding: 0 160px; width: 660px; } #grid.grid-2 div.vert{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </style> </head> <body> <div id="content" role="main"> <h1>#grid <em>v6</em></h1> <p class="summary"><em>Fri, 10 Jun 2011<span>:</span></em> This is a little tool we created for our <a href="http://analog.coop/">Analog&#160;holding&#160;page</a>. It inserts a <a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a> in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit <span class="key">G</span> on your keyboard.</p> <h2>Download</h2> <p id="download"><a href="http://github.com/dotjay/hashgrid/downloads">Download #grid</a> from <a href="http://github.com/dotjay/hashgrid">GitHub</a></p> <h2 id="features">Features</h2> <ul> <li>Adaptable for all layout widths and alignments</li> <li>Adaptable for any vertical rhythm value</li> <li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li> <li>Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters</li> </ul> <p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p> <h2 id="installation">Installation</h2> <ol> <li><h3>Copy the <a href="http://github.com/dotjay/hashgrid/blob/v6/hashgrid.js">hashgrid.js</a> script to your project</h3></li> <li><h3>Add the script to your page(s) just inside the <code>&#60;/body&#62;</code> tag</h3> <textarea id="javascript-code" cols="68" rows="8" readonly="readonly"> &#60;!-- Grab latest version of jQuery --&#62; &#60;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"&#62; &#60;/script&#62; &#60;!-- Include the hashgrid script --&#62; &#60;script type="text/javascript" src="hashgrid.js"&#62;&#60;/script&#62;</textarea></li> <li><h3>Add the CSS to your page(s)</h3> <textarea id="css-code" cols="68" rows="64" readonly="readonly"> /** * Grid */ #grid{ /* Dimensions - same width as your grid with gutters */ width: 980px; /* Grid (left-aligned) position: absolute; top: 0; left: 0; */ /* Grid (centered) */ position: absolute; top: 0; left: 50%; margin-left: -490px; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ #grid div.vert{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-right: 19px; } #grid div.vert.first-line{ margin-left: 19px; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ #grid div.horiz{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option in the hashgrid.js file. */ #grid.grid-1 div.vert{ /* Vertical grid line colour for grid 1 */ border-color: darkturquoise; } #grid.grid-2{ /* Adjustments */ padding: 0 160px; width: 660px; } #grid.grid-2 div.vert{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </textarea></li> <li><h3>Modify #grid to suit your needs</h3> <p>The CSS and JavaScript is annotated to help you.</p></li> </ol> <h2 id="usage">Usage</h2> <p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p> <dl> <dt><span class="key">G</span></dt> <dd>Show the grid until you release.</dd> <dt><span class="key">G</span> + <span class="key">H</span></dt> <dd>Show and hold the grid (<span class="key">G</span> will remove it again).</dd> <dt><span class="key">G</span> + <span class="key">F</span></dt> <dd>Toggle the grid to the foreground and back. Pressing <span class="key">F</span> while the grid is held also works.</dd> <dt><span class="key">G</span> + <span class="key">J</span></dt> <dd>Jump to the next grid. Pressing <span class="key">J</span> while the grid is held also works.</dd> </dl> <p><em>N.B. A cookie conveniently remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page except in Chrome v4, Safari v4, Firefox v3.6, or more recent versions.</em></p> <h2 id="release-notes">Release Notes</h2> <dl> <dt>v6&#8201;&#8212;&#8201;10 Jun 2011</dt> <dd>Minor release for optimisations, and now released under an Apache License.</dd> <dt>v5&#8201;&#8212;&#8201;3 Nov 2010</dt> <dd> <ul> <li>Vertical grid lines can now be set using CSS&#8230; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution.</li> <li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li> <li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback.</li> </ul> </dd> <dt>v4&#8201;&#8212;&#8201;29 Mar 2010</dt> <dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd> <dt>v3&#8201;&#8212;&#8201;22 Feb 2010</dt> <dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd> <dt>v2&#8201;&#8212;&#8201;2 Feb 2010</dt> <dd>Keys are now more easily configured (see top of hashgrid.js). Renamed the GridOverlay object to hashgrid. Fixed crash when using with disabled CSS.</dd> <dt>v1&#8201;&#8212;&#8201;21 Dec 2009</dt> <dd>First release.</dd> </dl> <h2 id="known-issues">Known Issues</h2> <ul> <li><del>IE 8: Fully functional, but the default <span class="key">ALT</span> + <span class="key">G</span> + <span class="key">ENTER</span> shortcut puts IE into full screen mode. Hit <span class="key">ALT</span> + <span class="key">ENTER</span> to toggle full screen mode off again.</del><ins datetime="2010-02-22"> The default keyboard shortcuts have been changed.</ins></li> <li>IE 6: The grid is always in the foreground.</li> <li>Opera 9/10: Using <span class="key">CTRL</span> or <span class="key">ALT</span> as a modifier key will not work due to different key handling by the browser.</li> </ul> <h2 id="license">License</h2> -<p>Released under an <a href="http://www.apache.org/licenses/LICENSE-2.0.html">Apache License (Version 2.0)</a>, which essentially means that you&#8217;re free to copy, modify and distribute it for any project so long as you provide clear attribution to Analog. <a href="http://analog.coop/#talk-to-us">Contact us</a> if you need a different license.</p> + +<p>Copyright 2011 Analog Coop Limited</p> + +<p>Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at<br /><br /> + +<a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a></p> + +<p>Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License.</p> + +<p>This essentially means that you&#8217;re free to copy, modify and distribute it for any project so long as you provide clear attribution to Analog Coop Limited. <a href="http://analog.coop/#talk-to-us">Contact us</a> if you need a different license.</p> <div id="footer" role="contentinfo"> <p>#grid is an <a href="http://analog.coop/">Analog</a> gig. It was conceived by <a href="http://jontangerine.com/">Jon Tan</a>, and built by <a href="http://accessibility.co.uk/">Jon Gibbins</a>, in cahoots with our <a href="http://analog.coop#is">fine friends</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p> </div> </div> <!-- Grab latest version of jQuery --> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script> <!-- Include the hashgrid script --> <script type="text/javascript" src="hashgrid.js"></script> </body> </html>
dotjay/hashgrid
c7682bc9e7a8042b59dc2bf0dfb294f07df0bb56
Version 6 (minor release)
diff --git a/hashgrid.js b/hashgrid.js index 39f95b7..420e6a0 100644 --- a/hashgrid.js +++ b/hashgrid.js @@ -1,401 +1,401 @@ /** * hashgrid (jQuery version) * http://github.com/dotjay/hashgrid - * Version 5, 3 Nov 2010 + * Version 6, 10 Jun 2011 * Written by Jon Gibbins at Analog, http://analog.coop/ * * Contibutors: * Sean Coates, http://seancoates.com/ * Phil Dokas, http://jetless.org/ * Andrew Jaswa, http://andrewjaswa.com/ * * License: * http://www.apache.org/licenses/LICENSE-2.0.html * * // Using a basic #grid setup * var grid = new hashgrid(); * * // Using #grid with a custom id (e.g. #mygrid) * var grid = new hashgrid("mygrid"); * * // Using #grid with additional options * var grid = new hashgrid({ * id: 'mygrid', // id for the grid container * modifierKey: 'alt', // optional 'ctrl', 'alt' or 'shift' * showGridKey: 's', // key to show the grid * holdGridKey: 'enter', // key to hold the grid in place * foregroundKey: 'f', // key to toggle foreground/background * jumpGridsKey: 'd', // key to cycle through the grid classes * numberOfGrids: 2, // number of grid classes used * classPrefix: 'class', // prefix for the grid classes * cookiePrefix: 'mygrid' // prefix for the cookie name * }); */ if (typeof jQuery == "undefined") { alert("Hashgrid: jQuery not loaded. Make sure it's linked to your pages."); } /** * hashgrid overlay */ var hashgrid = function(set) { var options = { id: 'grid', // id for the grid container modifierKey: null, // optional 'ctrl', 'alt' or 'shift' showGridKey: 'g', // key to show the grid holdGridKey: 'h', // key to hold the grid in place foregroundKey: 'f', // key to toggle foreground/background jumpGridsKey: 'j', // key to cycle through the grid classes numberOfGrids: 1, // number of grid classes used classPrefix: 'grid-', // prefix for the grid classes cookiePrefix: 'hashgrid'// prefix for the cookie name }, classNumber = 1, gridLines, gridWidth, i, line, lineHeight, numGridLines, overlay, overlayCookie, overlayEl, overlayOn = false, overlayVert, overlayZState = 'B', overlayZBackground = -1, overlayZForeground = 9999, pageHeight, setKey, state, sticky = false, top; // Apply options if (typeof set == 'object') { for (setKey in set) { options[setKey] = set[setKey]; } } else if (typeof set == 'string') { options.id = set; } // Remove any conflicting overlay if ($('#' + options.id).length > 0) { $('#' + options.id).remove(); } // Create overlay, hidden before adding to DOM overlayEl = $('<div></div>'); overlayEl .attr('id', options.id) .css({ display: 'none', 'pointer-events': 'none' }); $("body").prepend(overlayEl); overlay = $('#' + options.id); // Unless a custom z-index is set, ensure the overlay will be behind everything if (overlay.css('z-index') == 'auto') overlay.css('z-index', overlayZBackground); // Override the default overlay height with the actual page height pageHeight = parseFloat($(document).height()); overlay.height(pageHeight); // Add the first grid line so that we can measure it overlay.append('<div id="' + options.id + '-horiz" class="horiz first-line">'); // Position off-screen and display to calculate height top = overlay.css("top"); overlay.css({ top: "-999px", display: "block" }); // Calculate the number of grid lines needed line = $('#' + options.id + '-horiz'); lineHeight = line.outerHeight(); // Hide and reset top overlay.css({ display: "none", top: top }); // Break on zero line height if (lineHeight <= 0) { return false; } // Add the remaining grid lines numGridLines = Math.floor(pageHeight / lineHeight); gridLines = ''; for (i = numGridLines - 1; i >= 1; i--) { gridLines += '<div class="horiz"></div>'; } overlay.append(gridLines); // vertical grid overlay.append($('<div class="vert-container"></div>')); overlayVert = overlay.children('.vert-container'); gridWidth = overlay.width(); overlayVert.css({width: gridWidth, position: 'absolute', top: 0}); overlayVert.append('<div class="vert first-line">&nbsp;</div>'); // 30 is an arbitrarily large number... // can't calculate the margin width properly gridLines = ''; for (i = 0; i < 30; i++) { gridLines += '<div class="vert">&nbsp;</div>'; } overlayVert.append(gridLines); overlayVert.children() .height(pageHeight) .css({ display: 'inline-block' }); // Check for saved state overlayCookie = readCookie(options.cookiePrefix + options.id); if (typeof overlayCookie == 'string') { state = overlayCookie.split(','); state[2] = Number(state[2]); if ((typeof state[2] == 'number') && !isNaN(state[2])) { classNumber = state[2].toFixed(0); overlay.addClass(options.classPrefix + classNumber); } if (state[1] == 'F') { overlayZState = 'F'; overlay.css('z-index', overlayZForeground); } if (state[0] == '1') { overlayOn = true; sticky = true; showOverlay(); } } else { overlay.addClass(options.classPrefix + classNumber); } // Keyboard controls $(document).bind('keydown', keydownHandler); $(document).bind('keyup', keyupHandler); /** * Helpers */ function getModifier(e) { if (options.modifierKey == null) return true; // Bypass by default var m = true; switch(options.modifierKey) { case 'ctrl': m = (e.ctrlKey ? e.ctrlKey : false); break; case 'alt': m = (e.altKey ? e.altKey : false); break; case 'shift': m = (e.shiftKey ? e.shiftKey : false); break; } return m; } function getKey(e) { var k = false, c = (e.keyCode ? e.keyCode : e.which); // Handle keywords if (c == 13) k = 'enter'; // Handle letters else k = String.fromCharCode(c).toLowerCase(); return k; } function saveState() { createCookie(options.cookiePrefix + options.id, (sticky ? '1' : '0') + ',' + overlayZState + ',' + classNumber, 1); } function showOverlay() { overlay.show(); overlayVert.css({width: overlay.width()}); // hide any vertical blocks that aren't at the top of the viewport overlayVert.children('.vert').each(function () { $(this).css('display','inline-block'); if ($(this).offset().top > 0) { $(this).hide(); } }); } /** * Event handlers */ function keydownHandler(e) { var k, m, source = e.target.tagName.toLowerCase(); if ((source == 'input') || (source == 'textarea') || (source == 'select')) { return true; } m = getModifier(e); if (!m) { return true; } k = getKey(e); if (!k) { return true; } switch(k) { case options.showGridKey: if (!overlayOn) { showOverlay(); overlayOn = true; } else if (sticky) { overlay.hide(); overlayOn = false; sticky = false; saveState(); } break; case options.holdGridKey: if (overlayOn && !sticky) { // Turn sticky overlay on sticky = true; saveState(); } break; case options.foregroundKey: if (overlayOn) { // Toggle sticky overlay z-index if (overlay.css('z-index') == overlayZForeground) { overlay.css('z-index', overlayZBackground); overlayZState = 'B'; } else { overlay.css('z-index', overlayZForeground); overlayZState = 'F'; } saveState(); } break; case options.jumpGridsKey: if (overlayOn && (options.numberOfGrids > 1)) { // Cycle through the available grids overlay.removeClass(options.classPrefix + classNumber); classNumber++; if (classNumber > options.numberOfGrids) classNumber = 1; overlay.addClass(options.classPrefix + classNumber); showOverlay(); if (/webkit/.test( navigator.userAgent.toLowerCase() )) { forceRepaint(); } saveState(); } break; } return true; } function keyupHandler(e) { var k, m = getModifier(e); if (!m) { return true; } k = getKey(e); if (k && (k == options.showGridKey) && !sticky) { overlay.hide(); overlayOn = false; } return true; } /** * Cookie functions * * By Peter-Paul Koch: * http://www.quirksmode.org/js/cookies.html */ function createCookie(name, value, days) { var date, expires = ""; if (days) { date = new Date(); date.setTime( date.getTime() + (days*24*60*60*1000) ); expires = "; expires=" + date.toGMTString(); } document.cookie = name + "=" + value + expires + "; path=/"; } function readCookie(name) { var c, ca = document.cookie.split(';'), i = 0, len = ca.length, nameEQ = name + "="; for (; i < len; i++) { c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1, c.length); } if (c.indexOf(nameEQ) == 0) { return c.substring(nameEQ.length, c.length); } } return null; } function eraseCookie(name) { createCookie(name, "", -1); } /** * Forces a repaint (because WebKit has issues) * http://www.sitepoint.com/forums/showthread.php?p=4538763 * http://www.phpied.com/the-new-game-show-will-it-reflow/ */ function forceRepaint() { var ss = document.styleSheets[0]; try { ss.addRule('.xxxxxx', 'position: relative'); ss.removeRule(ss.rules.length - 1); } catch(e) {} } return {}; }; /** * You can call hashgrid from your own code, but it's loaded here as * an example for your convenience. */ $(document).ready(function() { var grid = new hashgrid({ numberOfGrids: 2 }); }); diff --git a/index.htm b/index.htm index 06eec28..b9d74b6 100644 --- a/index.htm +++ b/index.htm @@ -1,427 +1,429 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>#grid</title> <style type="text/css"> /* Putting inline rules here so the document can be downloaded with style */ body{ font-size: 1em; line-height: 1.25; font-family: Arial, sans-serif; background: White; color: DimGray; margin: 0; padding: 0 20px; } #content{ font-size: 16px; line-height: 20px; position: relative; } #content{ width: 620px; margin: 0 auto; } #footer{ border-top: 1px dotted DarkGray; padding-top: 19px; } h1, h2{ color: Black; font-weight: normal; } h1{ font-size: 36px; line-height: 40px; margin: 40px 0 20px; padding-bottom: 19px; border-bottom: 1px dotted DarkGray; } h1 em{ font-style: normal; color: DarkGray; font-size: 16px; line-height: 20px; margin: 0 0 20px; } h2, h3{ font-size: 16px; font-weight: 700; line-height: 20px; margin: 0 0 20px; } h3{ font-weight: 300; } a:link, a:visited{ color: Black; text-decoration: none; padding: 0 2px; background-color: WhiteSmoke; border-bottom: 1px solid Gold; } a:focus{ outline: none; } a:focus, a:hover, a:active{ background-color: Khaki; border-bottom: 1px solid GoldenRod; } p, ul{ padding: 0; margin: 0 0 20px; } dl, ol{ padding: 0; margin: 0; } ul{ list-style: circle; } ol li{ margin-bottom: 20px; } dd{ margin: 0 0 20px 0; } del{ text-decoration: line-through; opacity: 0.75; } ins{ text-decoration: none; } code{ font-size: 14px; line-height: 1; } textarea{ font-family: 'Courier New', monospace; font-size: 14px; line-height: 20px; display: block; width: 600px; margin: 0 0 20px; padding: 0 0 0 15px; border: 0; color: Black; background: Gainsboro; border-left: 5px solid DarkGray; } #javascript-code{ height: 180px; } #css-code{ height: 1300px; } .summary em{ font-style: normal; position: absolute; color: DarkGray; right: 0; top: 18px; width: 140px; } .summary em span{ position: absolute; left: -9999px; } #download{ line-height: 60px; padding: 0 40px 0 15px; border-left: 5px solid DarkGray; background: Gainsboro; color: DimGray; } span.key{ color: Black; text-transform: uppercase; } </style> <!-- Set styles --> <style type="text/css"> /** * Grid */ #grid{ /* Dimensions - same width as your grid with gutters */ width: 980px; /* Grid (left-aligned) position: absolute; top: 0; left: 0; */ /* Grid (centered) */ position: absolute; top: 0; left: 50%; margin-left: -490px; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ #grid div.vert{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-right: 19px; } #grid div.vert.first-line{ margin-left: 19px; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ #grid div.horiz{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option in the hashgrid.js file. */ #grid.grid-1 div.vert{ /* Vertical grid line colour for grid 1 */ border-color: darkturquoise; } #grid.grid-2{ /* Adjustments */ padding: 0 160px; width: 660px; } #grid.grid-2 div.vert{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </style> </head> <body> <div id="content" role="main"> -<h1>#grid <em>v5</em></h1> +<h1>#grid <em>v6</em></h1> -<p class="summary"><em>Wed, 3 Nov 2010<span>:</span></em> This is a little tool we created for our <a href="http://analog.coop/">Analog&#160;holding&#160;page</a>. It inserts a <a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a> in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit <span class="key">G</span> on your keyboard.</p> +<p class="summary"><em>Fri, 10 Jun 2011<span>:</span></em> This is a little tool we created for our <a href="http://analog.coop/">Analog&#160;holding&#160;page</a>. It inserts a <a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a> in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit <span class="key">G</span> on your keyboard.</p> <h2>Download</h2> <p id="download"><a href="http://github.com/dotjay/hashgrid/downloads">Download #grid</a> from <a href="http://github.com/dotjay/hashgrid">GitHub</a></p> <h2 id="features">Features</h2> <ul> <li>Adaptable for all layout widths and alignments</li> <li>Adaptable for any vertical rhythm value</li> <li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li> <li>Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters</li> </ul> <p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p> <h2 id="installation">Installation</h2> <ol> -<li><h3>Copy the <a href="http://github.com/dotjay/hashgrid/blob/v5/hashgrid.js">hashgrid.js</a> script to your project</h3></li> +<li><h3>Copy the <a href="http://github.com/dotjay/hashgrid/blob/v6/hashgrid.js">hashgrid.js</a> script to your project</h3></li> <li><h3>Add the script to your page(s) just inside the <code>&#60;/body&#62;</code> tag</h3> <textarea id="javascript-code" cols="68" rows="8" readonly="readonly"> &#60;!-- Grab latest version of jQuery --&#62; &#60;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"&#62; &#60;/script&#62; &#60;!-- Include the hashgrid script --&#62; &#60;script type="text/javascript" src="hashgrid.js"&#62;&#60;/script&#62;</textarea></li> <li><h3>Add the CSS to your page(s)</h3> <textarea id="css-code" cols="68" rows="64" readonly="readonly"> /** * Grid */ #grid{ /* Dimensions - same width as your grid with gutters */ width: 980px; /* Grid (left-aligned) position: absolute; top: 0; left: 0; */ /* Grid (centered) */ position: absolute; top: 0; left: 50%; margin-left: -490px; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ #grid div.vert{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-right: 19px; } #grid div.vert.first-line{ margin-left: 19px; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ #grid div.horiz{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option in the hashgrid.js file. */ #grid.grid-1 div.vert{ /* Vertical grid line colour for grid 1 */ border-color: darkturquoise; } #grid.grid-2{ /* Adjustments */ padding: 0 160px; width: 660px; } #grid.grid-2 div.vert{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </textarea></li> <li><h3>Modify #grid to suit your needs</h3> <p>The CSS and JavaScript is annotated to help you.</p></li> </ol> <h2 id="usage">Usage</h2> <p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p> <dl> <dt><span class="key">G</span></dt> <dd>Show the grid until you release.</dd> <dt><span class="key">G</span> + <span class="key">H</span></dt> <dd>Show and hold the grid (<span class="key">G</span> will remove it again).</dd> <dt><span class="key">G</span> + <span class="key">F</span></dt> <dd>Toggle the grid to the foreground and back. Pressing <span class="key">F</span> while the grid is held also works.</dd> <dt><span class="key">G</span> + <span class="key">J</span></dt> <dd>Jump to the next grid. Pressing <span class="key">J</span> while the grid is held also works.</dd> </dl> <p><em>N.B. A cookie conveniently remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page except in Chrome v4, Safari v4, Firefox v3.6, or more recent versions.</em></p> <h2 id="release-notes">Release Notes</h2> <dl> +<dt>v6&#8201;&#8212;&#8201;10 Jun 2011</dt> +<dd>Minor release for optimisations, and now released under an Apache License.</dd> <dt>v5&#8201;&#8212;&#8201;3 Nov 2010</dt> <dd> <ul> <li>Vertical grid lines can now be set using CSS&#8230; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution.</li> <li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li> <li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback.</li> </ul> </dd> <dt>v4&#8201;&#8212;&#8201;29 Mar 2010</dt> <dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd> <dt>v3&#8201;&#8212;&#8201;22 Feb 2010</dt> <dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd> <dt>v2&#8201;&#8212;&#8201;2 Feb 2010</dt> <dd>Keys are now more easily configured (see top of hashgrid.js). Renamed the GridOverlay object to hashgrid. Fixed crash when using with disabled CSS.</dd> <dt>v1&#8201;&#8212;&#8201;21 Dec 2009</dt> <dd>First release.</dd> </dl> <h2 id="known-issues">Known Issues</h2> <ul> <li><del>IE 8: Fully functional, but the default <span class="key">ALT</span> + <span class="key">G</span> + <span class="key">ENTER</span> shortcut puts IE into full screen mode. Hit <span class="key">ALT</span> + <span class="key">ENTER</span> to toggle full screen mode off again.</del><ins datetime="2010-02-22"> The default keyboard shortcuts have been changed.</ins></li> <li>IE 6: The grid is always in the foreground.</li> <li>Opera 9/10: Using <span class="key">CTRL</span> or <span class="key">ALT</span> as a modifier key will not work due to different key handling by the browser.</li> </ul> <h2 id="license">License</h2> <p>Released under an <a href="http://www.apache.org/licenses/LICENSE-2.0.html">Apache License (Version 2.0)</a>, which essentially means that you&#8217;re free to copy, modify and distribute it for any project so long as you provide clear attribution to Analog. <a href="http://analog.coop/#talk-to-us">Contact us</a> if you need a different license.</p> <div id="footer" role="contentinfo"> <p>#grid is an <a href="http://analog.coop/">Analog</a> gig. It was conceived by <a href="http://jontangerine.com/">Jon Tan</a>, and built by <a href="http://accessibility.co.uk/">Jon Gibbins</a>, in cahoots with our <a href="http://analog.coop#is">fine friends</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p> </div> </div> <!-- Grab latest version of jQuery --> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script> <!-- Include the hashgrid script --> <script type="text/javascript" src="hashgrid.js"></script> </body> </html>
dotjay/hashgrid
e9235d81a87f6158b5c657f41c633f772e15ce7a
Use Apache License
diff --git a/README.md b/README.md index 6446868..399338c 100644 --- a/README.md +++ b/README.md @@ -1,17 +1,20 @@ # #grid # A little tool that inserts a layout grid in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. ## Features ## * Adaptable for all layout widths and alignments * Adaptable for any vertical rhythm value * Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids * Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters Notes on installation and usage can be found in the included index.htm file. ## License ## -Released under a Creative Commons Attribution-Share Alike License, which essentially means that you’re free to copy it and adapt it. Get in touch if you need a different license. +Released under an Apache License (Version 2.0), which essentially means that you're free to copy, modify and distribute it for any project so long as you provide clear attribution to Analog. +http://www.apache.org/licenses/LICENSE-2.0.html +Contact us if you need a different license. +http://analog.coop/ diff --git a/hashgrid.js b/hashgrid.js index b14b775..39f95b7 100644 --- a/hashgrid.js +++ b/hashgrid.js @@ -1,396 +1,401 @@ /** * hashgrid (jQuery version) * http://github.com/dotjay/hashgrid * Version 5, 3 Nov 2010 - * Written by Jon Gibbins, dotjay.co.uk, accessibility.co.uk + * Written by Jon Gibbins at Analog, http://analog.coop/ + * * Contibutors: - * Sean Coates, seancoates.com - * Phil Dokas, jetless.org + * Sean Coates, http://seancoates.com/ + * Phil Dokas, http://jetless.org/ + * Andrew Jaswa, http://andrewjaswa.com/ + * + * License: + * http://www.apache.org/licenses/LICENSE-2.0.html * * // Using a basic #grid setup * var grid = new hashgrid(); * * // Using #grid with a custom id (e.g. #mygrid) * var grid = new hashgrid("mygrid"); * * // Using #grid with additional options * var grid = new hashgrid({ * id: 'mygrid', // id for the grid container * modifierKey: 'alt', // optional 'ctrl', 'alt' or 'shift' * showGridKey: 's', // key to show the grid * holdGridKey: 'enter', // key to hold the grid in place * foregroundKey: 'f', // key to toggle foreground/background * jumpGridsKey: 'd', // key to cycle through the grid classes * numberOfGrids: 2, // number of grid classes used * classPrefix: 'class', // prefix for the grid classes * cookiePrefix: 'mygrid' // prefix for the cookie name * }); */ if (typeof jQuery == "undefined") { alert("Hashgrid: jQuery not loaded. Make sure it's linked to your pages."); } /** * hashgrid overlay */ var hashgrid = function(set) { var options = { id: 'grid', // id for the grid container modifierKey: null, // optional 'ctrl', 'alt' or 'shift' showGridKey: 'g', // key to show the grid holdGridKey: 'h', // key to hold the grid in place foregroundKey: 'f', // key to toggle foreground/background jumpGridsKey: 'j', // key to cycle through the grid classes numberOfGrids: 1, // number of grid classes used classPrefix: 'grid-', // prefix for the grid classes cookiePrefix: 'hashgrid'// prefix for the cookie name }, classNumber = 1, gridLines, gridWidth, i, line, lineHeight, numGridLines, overlay, overlayCookie, overlayEl, overlayOn = false, overlayVert, overlayZState = 'B', overlayZBackground = -1, overlayZForeground = 9999, pageHeight, setKey, state, sticky = false, top; // Apply options if (typeof set == 'object') { for (setKey in set) { options[setKey] = set[setKey]; } } else if (typeof set == 'string') { options.id = set; } // Remove any conflicting overlay if ($('#' + options.id).length > 0) { $('#' + options.id).remove(); } // Create overlay, hidden before adding to DOM overlayEl = $('<div></div>'); overlayEl .attr('id', options.id) .css({ display: 'none', 'pointer-events': 'none' }); $("body").prepend(overlayEl); overlay = $('#' + options.id); // Unless a custom z-index is set, ensure the overlay will be behind everything if (overlay.css('z-index') == 'auto') overlay.css('z-index', overlayZBackground); // Override the default overlay height with the actual page height pageHeight = parseFloat($(document).height()); overlay.height(pageHeight); // Add the first grid line so that we can measure it overlay.append('<div id="' + options.id + '-horiz" class="horiz first-line">'); // Position off-screen and display to calculate height top = overlay.css("top"); overlay.css({ top: "-999px", display: "block" }); // Calculate the number of grid lines needed line = $('#' + options.id + '-horiz'); lineHeight = line.outerHeight(); // Hide and reset top overlay.css({ display: "none", top: top }); // Break on zero line height if (lineHeight <= 0) { return false; } // Add the remaining grid lines numGridLines = Math.floor(pageHeight / lineHeight); gridLines = ''; for (i = numGridLines - 1; i >= 1; i--) { gridLines += '<div class="horiz"></div>'; } overlay.append(gridLines); // vertical grid overlay.append($('<div class="vert-container"></div>')); overlayVert = overlay.children('.vert-container'); gridWidth = overlay.width(); overlayVert.css({width: gridWidth, position: 'absolute', top: 0}); overlayVert.append('<div class="vert first-line">&nbsp;</div>'); // 30 is an arbitrarily large number... // can't calculate the margin width properly gridLines = ''; for (i = 0; i < 30; i++) { gridLines += '<div class="vert">&nbsp;</div>'; } overlayVert.append(gridLines); overlayVert.children() .height(pageHeight) .css({ display: 'inline-block' }); // Check for saved state overlayCookie = readCookie(options.cookiePrefix + options.id); if (typeof overlayCookie == 'string') { state = overlayCookie.split(','); state[2] = Number(state[2]); if ((typeof state[2] == 'number') && !isNaN(state[2])) { classNumber = state[2].toFixed(0); overlay.addClass(options.classPrefix + classNumber); } if (state[1] == 'F') { overlayZState = 'F'; overlay.css('z-index', overlayZForeground); } if (state[0] == '1') { overlayOn = true; sticky = true; showOverlay(); } } else { overlay.addClass(options.classPrefix + classNumber); } // Keyboard controls $(document).bind('keydown', keydownHandler); $(document).bind('keyup', keyupHandler); /** * Helpers */ function getModifier(e) { if (options.modifierKey == null) return true; // Bypass by default var m = true; switch(options.modifierKey) { case 'ctrl': m = (e.ctrlKey ? e.ctrlKey : false); break; case 'alt': m = (e.altKey ? e.altKey : false); break; case 'shift': m = (e.shiftKey ? e.shiftKey : false); break; } return m; } function getKey(e) { var k = false, c = (e.keyCode ? e.keyCode : e.which); // Handle keywords if (c == 13) k = 'enter'; // Handle letters else k = String.fromCharCode(c).toLowerCase(); return k; } function saveState() { createCookie(options.cookiePrefix + options.id, (sticky ? '1' : '0') + ',' + overlayZState + ',' + classNumber, 1); } function showOverlay() { overlay.show(); overlayVert.css({width: overlay.width()}); // hide any vertical blocks that aren't at the top of the viewport overlayVert.children('.vert').each(function () { $(this).css('display','inline-block'); if ($(this).offset().top > 0) { $(this).hide(); } }); } /** * Event handlers */ function keydownHandler(e) { var k, m, source = e.target.tagName.toLowerCase(); if ((source == 'input') || (source == 'textarea') || (source == 'select')) { return true; } m = getModifier(e); if (!m) { return true; } k = getKey(e); if (!k) { return true; } switch(k) { case options.showGridKey: if (!overlayOn) { showOverlay(); overlayOn = true; } else if (sticky) { overlay.hide(); overlayOn = false; sticky = false; saveState(); } break; case options.holdGridKey: if (overlayOn && !sticky) { // Turn sticky overlay on sticky = true; saveState(); } break; case options.foregroundKey: if (overlayOn) { // Toggle sticky overlay z-index if (overlay.css('z-index') == overlayZForeground) { overlay.css('z-index', overlayZBackground); overlayZState = 'B'; } else { overlay.css('z-index', overlayZForeground); overlayZState = 'F'; } saveState(); } break; case options.jumpGridsKey: if (overlayOn && (options.numberOfGrids > 1)) { // Cycle through the available grids overlay.removeClass(options.classPrefix + classNumber); classNumber++; if (classNumber > options.numberOfGrids) classNumber = 1; overlay.addClass(options.classPrefix + classNumber); showOverlay(); if (/webkit/.test( navigator.userAgent.toLowerCase() )) { forceRepaint(); } saveState(); } break; } return true; } function keyupHandler(e) { var k, m = getModifier(e); if (!m) { return true; } k = getKey(e); if (k && (k == options.showGridKey) && !sticky) { overlay.hide(); overlayOn = false; } return true; } /** * Cookie functions * * By Peter-Paul Koch: * http://www.quirksmode.org/js/cookies.html */ function createCookie(name, value, days) { var date, expires = ""; if (days) { date = new Date(); date.setTime( date.getTime() + (days*24*60*60*1000) ); expires = "; expires=" + date.toGMTString(); } document.cookie = name + "=" + value + expires + "; path=/"; } function readCookie(name) { var c, ca = document.cookie.split(';'), i = 0, len = ca.length, nameEQ = name + "="; for (; i < len; i++) { c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1, c.length); } if (c.indexOf(nameEQ) == 0) { return c.substring(nameEQ.length, c.length); } } return null; } function eraseCookie(name) { createCookie(name, "", -1); } /** * Forces a repaint (because WebKit has issues) * http://www.sitepoint.com/forums/showthread.php?p=4538763 * http://www.phpied.com/the-new-game-show-will-it-reflow/ */ function forceRepaint() { var ss = document.styleSheets[0]; try { ss.addRule('.xxxxxx', 'position: relative'); ss.removeRule(ss.rules.length - 1); } catch(e) {} } return {}; }; /** * You can call hashgrid from your own code, but it's loaded here as * an example for your convenience. */ $(document).ready(function() { var grid = new hashgrid({ numberOfGrids: 2 }); }); diff --git a/index.htm b/index.htm index 428f627..06eec28 100644 --- a/index.htm +++ b/index.htm @@ -1,427 +1,427 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>#grid</title> <style type="text/css"> /* Putting inline rules here so the document can be downloaded with style */ body{ font-size: 1em; line-height: 1.25; font-family: Arial, sans-serif; background: White; color: DimGray; margin: 0; padding: 0 20px; } #content{ font-size: 16px; line-height: 20px; position: relative; } #content{ width: 620px; margin: 0 auto; } #footer{ border-top: 1px dotted DarkGray; padding-top: 19px; } h1, h2{ color: Black; font-weight: normal; } h1{ font-size: 36px; line-height: 40px; margin: 40px 0 20px; padding-bottom: 19px; border-bottom: 1px dotted DarkGray; } h1 em{ font-style: normal; color: DarkGray; font-size: 16px; line-height: 20px; margin: 0 0 20px; } h2, h3{ font-size: 16px; font-weight: 700; line-height: 20px; margin: 0 0 20px; } h3{ font-weight: 300; } a:link, a:visited{ color: Black; text-decoration: none; padding: 0 2px; background-color: WhiteSmoke; border-bottom: 1px solid Gold; } a:focus{ outline: none; } a:focus, a:hover, a:active{ background-color: Khaki; border-bottom: 1px solid GoldenRod; } p, ul{ padding: 0; margin: 0 0 20px; } dl, ol{ padding: 0; margin: 0; } ul{ list-style: circle; } ol li{ margin-bottom: 20px; } dd{ margin: 0 0 20px 0; } del{ text-decoration: line-through; opacity: 0.75; } ins{ text-decoration: none; } code{ font-size: 14px; line-height: 1; } textarea{ font-family: 'Courier New', monospace; font-size: 14px; line-height: 20px; display: block; width: 600px; margin: 0 0 20px; padding: 0 0 0 15px; border: 0; color: Black; background: Gainsboro; border-left: 5px solid DarkGray; } #javascript-code{ height: 180px; } #css-code{ height: 1300px; } .summary em{ font-style: normal; position: absolute; color: DarkGray; right: 0; top: 18px; width: 140px; } .summary em span{ position: absolute; left: -9999px; } #download{ line-height: 60px; padding: 0 40px 0 15px; border-left: 5px solid DarkGray; background: Gainsboro; color: DimGray; } span.key{ color: Black; text-transform: uppercase; } </style> <!-- Set styles --> <style type="text/css"> /** * Grid */ #grid{ /* Dimensions - same width as your grid with gutters */ width: 980px; /* Grid (left-aligned) position: absolute; top: 0; left: 0; */ /* Grid (centered) */ position: absolute; top: 0; left: 50%; margin-left: -490px; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ #grid div.vert{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-right: 19px; } #grid div.vert.first-line{ margin-left: 19px; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ #grid div.horiz{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option in the hashgrid.js file. */ #grid.grid-1 div.vert{ /* Vertical grid line colour for grid 1 */ border-color: darkturquoise; } #grid.grid-2{ /* Adjustments */ padding: 0 160px; width: 660px; } #grid.grid-2 div.vert{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </style> </head> <body> <div id="content" role="main"> <h1>#grid <em>v5</em></h1> <p class="summary"><em>Wed, 3 Nov 2010<span>:</span></em> This is a little tool we created for our <a href="http://analog.coop/">Analog&#160;holding&#160;page</a>. It inserts a <a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a> in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit <span class="key">G</span> on your keyboard.</p> <h2>Download</h2> <p id="download"><a href="http://github.com/dotjay/hashgrid/downloads">Download #grid</a> from <a href="http://github.com/dotjay/hashgrid">GitHub</a></p> <h2 id="features">Features</h2> <ul> <li>Adaptable for all layout widths and alignments</li> <li>Adaptable for any vertical rhythm value</li> <li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li> <li>Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters</li> </ul> <p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p> <h2 id="installation">Installation</h2> <ol> <li><h3>Copy the <a href="http://github.com/dotjay/hashgrid/blob/v5/hashgrid.js">hashgrid.js</a> script to your project</h3></li> <li><h3>Add the script to your page(s) just inside the <code>&#60;/body&#62;</code> tag</h3> <textarea id="javascript-code" cols="68" rows="8" readonly="readonly"> &#60;!-- Grab latest version of jQuery --&#62; &#60;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"&#62; &#60;/script&#62; &#60;!-- Include the hashgrid script --&#62; &#60;script type="text/javascript" src="hashgrid.js"&#62;&#60;/script&#62;</textarea></li> <li><h3>Add the CSS to your page(s)</h3> <textarea id="css-code" cols="68" rows="64" readonly="readonly"> /** * Grid */ #grid{ /* Dimensions - same width as your grid with gutters */ width: 980px; /* Grid (left-aligned) position: absolute; top: 0; left: 0; */ /* Grid (centered) */ position: absolute; top: 0; left: 50%; margin-left: -490px; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ #grid div.vert{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-right: 19px; } #grid div.vert.first-line{ margin-left: 19px; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ #grid div.horiz{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option in the hashgrid.js file. */ #grid.grid-1 div.vert{ /* Vertical grid line colour for grid 1 */ border-color: darkturquoise; } #grid.grid-2{ /* Adjustments */ padding: 0 160px; width: 660px; } #grid.grid-2 div.vert{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </textarea></li> <li><h3>Modify #grid to suit your needs</h3> <p>The CSS and JavaScript is annotated to help you.</p></li> </ol> <h2 id="usage">Usage</h2> <p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p> <dl> <dt><span class="key">G</span></dt> <dd>Show the grid until you release.</dd> <dt><span class="key">G</span> + <span class="key">H</span></dt> <dd>Show and hold the grid (<span class="key">G</span> will remove it again).</dd> <dt><span class="key">G</span> + <span class="key">F</span></dt> <dd>Toggle the grid to the foreground and back. Pressing <span class="key">F</span> while the grid is held also works.</dd> <dt><span class="key">G</span> + <span class="key">J</span></dt> <dd>Jump to the next grid. Pressing <span class="key">J</span> while the grid is held also works.</dd> </dl> <p><em>N.B. A cookie conveniently remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page except in Chrome v4, Safari v4, Firefox v3.6, or more recent versions.</em></p> <h2 id="release-notes">Release Notes</h2> <dl> <dt>v5&#8201;&#8212;&#8201;3 Nov 2010</dt> <dd> <ul> <li>Vertical grid lines can now be set using CSS&#8230; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution.</li> <li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li> <li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback.</li> </ul> </dd> <dt>v4&#8201;&#8212;&#8201;29 Mar 2010</dt> <dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd> <dt>v3&#8201;&#8212;&#8201;22 Feb 2010</dt> <dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd> <dt>v2&#8201;&#8212;&#8201;2 Feb 2010</dt> <dd>Keys are now more easily configured (see top of hashgrid.js). Renamed the GridOverlay object to hashgrid. Fixed crash when using with disabled CSS.</dd> <dt>v1&#8201;&#8212;&#8201;21 Dec 2009</dt> <dd>First release.</dd> </dl> <h2 id="known-issues">Known Issues</h2> <ul> <li><del>IE 8: Fully functional, but the default <span class="key">ALT</span> + <span class="key">G</span> + <span class="key">ENTER</span> shortcut puts IE into full screen mode. Hit <span class="key">ALT</span> + <span class="key">ENTER</span> to toggle full screen mode off again.</del><ins datetime="2010-02-22"> The default keyboard shortcuts have been changed.</ins></li> <li>IE 6: The grid is always in the foreground.</li> <li>Opera 9/10: Using <span class="key">CTRL</span> or <span class="key">ALT</span> as a modifier key will not work due to different key handling by the browser.</li> </ul> <h2 id="license">License</h2> -<p>Released under a <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike License</a>, which essentially means that you&#8217;re free to copy it and adapt it. <a href="http://analog.coop/#talk-to-us">Contact us at Analog</a> if you need a different license.</p> +<p>Released under an <a href="http://www.apache.org/licenses/LICENSE-2.0.html">Apache License (Version 2.0)</a>, which essentially means that you&#8217;re free to copy, modify and distribute it for any project so long as you provide clear attribution to Analog. <a href="http://analog.coop/#talk-to-us">Contact us</a> if you need a different license.</p> <div id="footer" role="contentinfo"> <p>#grid is an <a href="http://analog.coop/">Analog</a> gig. It was conceived by <a href="http://jontangerine.com/">Jon Tan</a>, and built by <a href="http://accessibility.co.uk/">Jon Gibbins</a>, in cahoots with our <a href="http://analog.coop#is">fine friends</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p> </div> </div> <!-- Grab latest version of jQuery --> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script> <!-- Include the hashgrid script --> <script type="text/javascript" src="hashgrid.js"></script> </body> </html>
dotjay/hashgrid
26aec2d2f1ea2a48b0015d2bf132c0ea0ffbc346
Use more specific jQuery version
diff --git a/index.htm b/index.htm index 29c5a67..428f627 100644 --- a/index.htm +++ b/index.htm @@ -1,427 +1,427 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>#grid</title> <style type="text/css"> /* Putting inline rules here so the document can be downloaded with style */ body{ font-size: 1em; line-height: 1.25; font-family: Arial, sans-serif; background: White; color: DimGray; margin: 0; padding: 0 20px; } #content{ font-size: 16px; line-height: 20px; position: relative; } #content{ width: 620px; margin: 0 auto; } #footer{ border-top: 1px dotted DarkGray; padding-top: 19px; } h1, h2{ color: Black; font-weight: normal; } h1{ font-size: 36px; line-height: 40px; margin: 40px 0 20px; padding-bottom: 19px; border-bottom: 1px dotted DarkGray; } h1 em{ font-style: normal; color: DarkGray; font-size: 16px; line-height: 20px; margin: 0 0 20px; } h2, h3{ font-size: 16px; font-weight: 700; line-height: 20px; margin: 0 0 20px; } h3{ font-weight: 300; } a:link, a:visited{ color: Black; text-decoration: none; padding: 0 2px; background-color: WhiteSmoke; border-bottom: 1px solid Gold; } a:focus{ outline: none; } a:focus, a:hover, a:active{ background-color: Khaki; border-bottom: 1px solid GoldenRod; } p, ul{ padding: 0; margin: 0 0 20px; } dl, ol{ padding: 0; margin: 0; } ul{ list-style: circle; } ol li{ margin-bottom: 20px; } dd{ margin: 0 0 20px 0; } del{ text-decoration: line-through; opacity: 0.75; } ins{ text-decoration: none; } code{ font-size: 14px; line-height: 1; } textarea{ font-family: 'Courier New', monospace; font-size: 14px; line-height: 20px; display: block; width: 600px; margin: 0 0 20px; padding: 0 0 0 15px; border: 0; color: Black; background: Gainsboro; border-left: 5px solid DarkGray; } #javascript-code{ height: 180px; } #css-code{ height: 1300px; } .summary em{ font-style: normal; position: absolute; color: DarkGray; right: 0; top: 18px; width: 140px; } .summary em span{ position: absolute; left: -9999px; } #download{ line-height: 60px; padding: 0 40px 0 15px; border-left: 5px solid DarkGray; background: Gainsboro; color: DimGray; } span.key{ color: Black; text-transform: uppercase; } </style> <!-- Set styles --> <style type="text/css"> /** * Grid */ #grid{ /* Dimensions - same width as your grid with gutters */ width: 980px; /* Grid (left-aligned) position: absolute; top: 0; left: 0; */ /* Grid (centered) */ position: absolute; top: 0; left: 50%; margin-left: -490px; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ #grid div.vert{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-right: 19px; } #grid div.vert.first-line{ margin-left: 19px; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ #grid div.horiz{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option in the hashgrid.js file. */ #grid.grid-1 div.vert{ /* Vertical grid line colour for grid 1 */ border-color: darkturquoise; } #grid.grid-2{ /* Adjustments */ padding: 0 160px; width: 660px; } #grid.grid-2 div.vert{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </style> </head> <body> <div id="content" role="main"> <h1>#grid <em>v5</em></h1> <p class="summary"><em>Wed, 3 Nov 2010<span>:</span></em> This is a little tool we created for our <a href="http://analog.coop/">Analog&#160;holding&#160;page</a>. It inserts a <a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a> in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit <span class="key">G</span> on your keyboard.</p> <h2>Download</h2> <p id="download"><a href="http://github.com/dotjay/hashgrid/downloads">Download #grid</a> from <a href="http://github.com/dotjay/hashgrid">GitHub</a></p> <h2 id="features">Features</h2> <ul> <li>Adaptable for all layout widths and alignments</li> <li>Adaptable for any vertical rhythm value</li> <li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li> <li>Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters</li> </ul> <p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p> <h2 id="installation">Installation</h2> <ol> <li><h3>Copy the <a href="http://github.com/dotjay/hashgrid/blob/v5/hashgrid.js">hashgrid.js</a> script to your project</h3></li> <li><h3>Add the script to your page(s) just inside the <code>&#60;/body&#62;</code> tag</h3> <textarea id="javascript-code" cols="68" rows="8" readonly="readonly"> &#60;!-- Grab latest version of jQuery --&#62; &#60;script type="text/javascript" - src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"&#62; + src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"&#62; &#60;/script&#62; &#60;!-- Include the hashgrid script --&#62; &#60;script type="text/javascript" src="hashgrid.js"&#62;&#60;/script&#62;</textarea></li> <li><h3>Add the CSS to your page(s)</h3> <textarea id="css-code" cols="68" rows="64" readonly="readonly"> /** * Grid */ #grid{ /* Dimensions - same width as your grid with gutters */ width: 980px; /* Grid (left-aligned) position: absolute; top: 0; left: 0; */ /* Grid (centered) */ position: absolute; top: 0; left: 50%; margin-left: -490px; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ #grid div.vert{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-right: 19px; } #grid div.vert.first-line{ margin-left: 19px; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ #grid div.horiz{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option in the hashgrid.js file. */ #grid.grid-1 div.vert{ /* Vertical grid line colour for grid 1 */ border-color: darkturquoise; } #grid.grid-2{ /* Adjustments */ padding: 0 160px; width: 660px; } #grid.grid-2 div.vert{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </textarea></li> <li><h3>Modify #grid to suit your needs</h3> <p>The CSS and JavaScript is annotated to help you.</p></li> </ol> <h2 id="usage">Usage</h2> <p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p> <dl> <dt><span class="key">G</span></dt> <dd>Show the grid until you release.</dd> <dt><span class="key">G</span> + <span class="key">H</span></dt> <dd>Show and hold the grid (<span class="key">G</span> will remove it again).</dd> <dt><span class="key">G</span> + <span class="key">F</span></dt> <dd>Toggle the grid to the foreground and back. Pressing <span class="key">F</span> while the grid is held also works.</dd> <dt><span class="key">G</span> + <span class="key">J</span></dt> <dd>Jump to the next grid. Pressing <span class="key">J</span> while the grid is held also works.</dd> </dl> <p><em>N.B. A cookie conveniently remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page except in Chrome v4, Safari v4, Firefox v3.6, or more recent versions.</em></p> <h2 id="release-notes">Release Notes</h2> <dl> <dt>v5&#8201;&#8212;&#8201;3 Nov 2010</dt> <dd> <ul> <li>Vertical grid lines can now be set using CSS&#8230; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution.</li> <li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li> <li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback.</li> </ul> </dd> <dt>v4&#8201;&#8212;&#8201;29 Mar 2010</dt> <dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd> <dt>v3&#8201;&#8212;&#8201;22 Feb 2010</dt> <dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd> <dt>v2&#8201;&#8212;&#8201;2 Feb 2010</dt> <dd>Keys are now more easily configured (see top of hashgrid.js). Renamed the GridOverlay object to hashgrid. Fixed crash when using with disabled CSS.</dd> <dt>v1&#8201;&#8212;&#8201;21 Dec 2009</dt> <dd>First release.</dd> </dl> <h2 id="known-issues">Known Issues</h2> <ul> <li><del>IE 8: Fully functional, but the default <span class="key">ALT</span> + <span class="key">G</span> + <span class="key">ENTER</span> shortcut puts IE into full screen mode. Hit <span class="key">ALT</span> + <span class="key">ENTER</span> to toggle full screen mode off again.</del><ins datetime="2010-02-22"> The default keyboard shortcuts have been changed.</ins></li> <li>IE 6: The grid is always in the foreground.</li> <li>Opera 9/10: Using <span class="key">CTRL</span> or <span class="key">ALT</span> as a modifier key will not work due to different key handling by the browser.</li> </ul> <h2 id="license">License</h2> <p>Released under a <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike License</a>, which essentially means that you&#8217;re free to copy it and adapt it. <a href="http://analog.coop/#talk-to-us">Contact us at Analog</a> if you need a different license.</p> <div id="footer" role="contentinfo"> <p>#grid is an <a href="http://analog.coop/">Analog</a> gig. It was conceived by <a href="http://jontangerine.com/">Jon Tan</a>, and built by <a href="http://accessibility.co.uk/">Jon Gibbins</a>, in cahoots with our <a href="http://analog.coop#is">fine friends</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p> </div> </div> <!-- Grab latest version of jQuery --> -<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> +<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script> <!-- Include the hashgrid script --> <script type="text/javascript" src="hashgrid.js"></script> </body> </html>
dotjay/hashgrid
c559e75a780233bd1da3ecb1e8adcae04d5dac44
Linting
diff --git a/hashgrid.js b/hashgrid.js index 0401521..b14b775 100644 --- a/hashgrid.js +++ b/hashgrid.js @@ -1,344 +1,396 @@ /** * hashgrid (jQuery version) * http://github.com/dotjay/hashgrid * Version 5, 3 Nov 2010 * Written by Jon Gibbins, dotjay.co.uk, accessibility.co.uk * Contibutors: * Sean Coates, seancoates.com * Phil Dokas, jetless.org * * // Using a basic #grid setup * var grid = new hashgrid(); * * // Using #grid with a custom id (e.g. #mygrid) * var grid = new hashgrid("mygrid"); * * // Using #grid with additional options * var grid = new hashgrid({ * id: 'mygrid', // id for the grid container * modifierKey: 'alt', // optional 'ctrl', 'alt' or 'shift' * showGridKey: 's', // key to show the grid * holdGridKey: 'enter', // key to hold the grid in place * foregroundKey: 'f', // key to toggle foreground/background * jumpGridsKey: 'd', // key to cycle through the grid classes * numberOfGrids: 2, // number of grid classes used * classPrefix: 'class', // prefix for the grid classes * cookiePrefix: 'mygrid' // prefix for the cookie name * }); */ if (typeof jQuery == "undefined") { alert("Hashgrid: jQuery not loaded. Make sure it's linked to your pages."); } /** * hashgrid overlay */ var hashgrid = function(set) { var options = { - id: 'grid', // id for the grid container - modifierKey: null, // optional 'ctrl', 'alt' or 'shift' - showGridKey: 'g', // key to show the grid - holdGridKey: 'h', // key to hold the grid in place - foregroundKey: 'f', // key to toggle foreground/background - jumpGridsKey: 'j', // key to cycle through the grid classes - numberOfGrids: 1, // number of grid classes used - classPrefix: 'grid-', // prefix for the grid classes - cookiePrefix: 'hashgrid'// prefix for the cookie name - }; - var overlayOn = false, - sticky = false, + id: 'grid', // id for the grid container + modifierKey: null, // optional 'ctrl', 'alt' or 'shift' + showGridKey: 'g', // key to show the grid + holdGridKey: 'h', // key to hold the grid in place + foregroundKey: 'f', // key to toggle foreground/background + jumpGridsKey: 'j', // key to cycle through the grid classes + numberOfGrids: 1, // number of grid classes used + classPrefix: 'grid-', // prefix for the grid classes + cookiePrefix: 'hashgrid'// prefix for the cookie name + }, + classNumber = 1, + gridLines, + gridWidth, + i, + line, + lineHeight, + numGridLines, + overlay, + overlayCookie, + overlayEl, + overlayOn = false, + overlayVert, overlayZState = 'B', overlayZBackground = -1, overlayZForeground = 9999, - classNumber = 1; + pageHeight, + setKey, + state, + sticky = false, + top; // Apply options if (typeof set == 'object') { - var k; - for (k in set) options[k] = set[k]; + for (setKey in set) { + options[setKey] = set[setKey]; + } } else if (typeof set == 'string') { options.id = set; } // Remove any conflicting overlay if ($('#' + options.id).length > 0) { $('#' + options.id).remove(); } // Create overlay, hidden before adding to DOM - var overlayEl = $('<div></div>'); + overlayEl = $('<div></div>'); overlayEl .attr('id', options.id) .css({ display: 'none', 'pointer-events': 'none' }); $("body").prepend(overlayEl); - var overlay = $('#' + options.id); + overlay = $('#' + options.id); // Unless a custom z-index is set, ensure the overlay will be behind everything if (overlay.css('z-index') == 'auto') overlay.css('z-index', overlayZBackground); // Override the default overlay height with the actual page height - var pageHeight = parseFloat($(document).height()); + pageHeight = parseFloat($(document).height()); overlay.height(pageHeight); // Add the first grid line so that we can measure it overlay.append('<div id="' + options.id + '-horiz" class="horiz first-line">'); // Position off-screen and display to calculate height - var top = overlay.css("top"); + top = overlay.css("top"); overlay.css({ top: "-999px", display: "block" }); // Calculate the number of grid lines needed - var line = $('#' + options.id + '-horiz'), - lineHeight = line.outerHeight(); + line = $('#' + options.id + '-horiz'); + lineHeight = line.outerHeight(); // Hide and reset top overlay.css({ display: "none", top: top }); // Break on zero line height - if (lineHeight <= 0) return true; + if (lineHeight <= 0) { + return false; + } // Add the remaining grid lines - var i, numGridLines = Math.floor(pageHeight / lineHeight), - gridLines = ''; + numGridLines = Math.floor(pageHeight / lineHeight); + gridLines = ''; + for (i = numGridLines - 1; i >= 1; i--) { - gridLines += '<div class="horiz"></div>'; + gridLines += '<div class="horiz"></div>'; } - overlay.append(gridLines); + overlay.append(gridLines); // vertical grid overlay.append($('<div class="vert-container"></div>')); - var overlayVert = overlay.children('.vert-container'); - var gridWidth = overlay.width(); + overlayVert = overlay.children('.vert-container'); + gridWidth = overlay.width(); overlayVert.css({width: gridWidth, position: 'absolute', top: 0}); overlayVert.append('<div class="vert first-line">&nbsp;</div>'); // 30 is an arbitrarily large number... // can't calculate the margin width properly - var gridVert = ''; + gridLines = ''; for (i = 0; i < 30; i++) { - gridVert += '<div class="vert">&nbsp;</div>'; + gridLines += '<div class="vert">&nbsp;</div>'; } - overlayVert.append(gridVert); - + overlayVert.append(gridLines); overlayVert.children() .height(pageHeight) - .css({display: 'inline-block'}); + .css({ display: 'inline-block' }); // Check for saved state - var overlayCookie = readCookie(options.cookiePrefix + options.id); + overlayCookie = readCookie(options.cookiePrefix + options.id); if (typeof overlayCookie == 'string') { - var state = overlayCookie.split(','); + state = overlayCookie.split(','); state[2] = Number(state[2]); if ((typeof state[2] == 'number') && !isNaN(state[2])) { classNumber = state[2].toFixed(0); overlay.addClass(options.classPrefix + classNumber); } if (state[1] == 'F') { overlayZState = 'F'; overlay.css('z-index', overlayZForeground); } if (state[0] == '1') { overlayOn = true; sticky = true; showOverlay(); } } else { overlay.addClass(options.classPrefix + classNumber); } // Keyboard controls $(document).bind('keydown', keydownHandler); $(document).bind('keyup', keyupHandler); /** * Helpers */ function getModifier(e) { if (options.modifierKey == null) return true; // Bypass by default var m = true; switch(options.modifierKey) { case 'ctrl': m = (e.ctrlKey ? e.ctrlKey : false); break; case 'alt': m = (e.altKey ? e.altKey : false); break; case 'shift': m = (e.shiftKey ? e.shiftKey : false); break; } return m; } function getKey(e) { var k = false, c = (e.keyCode ? e.keyCode : e.which); // Handle keywords if (c == 13) k = 'enter'; // Handle letters else k = String.fromCharCode(c).toLowerCase(); return k; } function saveState() { createCookie(options.cookiePrefix + options.id, (sticky ? '1' : '0') + ',' + overlayZState + ',' + classNumber, 1); } function showOverlay() { overlay.show(); overlayVert.css({width: overlay.width()}); // hide any vertical blocks that aren't at the top of the viewport overlayVert.children('.vert').each(function () { $(this).css('display','inline-block'); if ($(this).offset().top > 0) { $(this).hide(); } }); } /** * Event handlers */ function keydownHandler(e) { - var source = e.target.tagName.toLowerCase(); - if ((source == 'input') || (source == 'textarea') || (source == 'select')) return true; - var m = getModifier(e); - if (!m) return true; - var k = getKey(e); - if (!k) return true; + var k, + m, + source = e.target.tagName.toLowerCase(); + + if ((source == 'input') || (source == 'textarea') || (source == 'select')) { + return true; + } + + m = getModifier(e); + if (!m) { + return true; + } + + k = getKey(e); + if (!k) { + return true; + } + switch(k) { case options.showGridKey: if (!overlayOn) { showOverlay(); overlayOn = true; } else if (sticky) { overlay.hide(); overlayOn = false; sticky = false; saveState(); } break; case options.holdGridKey: if (overlayOn && !sticky) { // Turn sticky overlay on sticky = true; saveState(); } break; case options.foregroundKey: if (overlayOn) { // Toggle sticky overlay z-index if (overlay.css('z-index') == overlayZForeground) { overlay.css('z-index', overlayZBackground); overlayZState = 'B'; } else { overlay.css('z-index', overlayZForeground); overlayZState = 'F'; } saveState(); } break; case options.jumpGridsKey: if (overlayOn && (options.numberOfGrids > 1)) { // Cycle through the available grids overlay.removeClass(options.classPrefix + classNumber); classNumber++; if (classNumber > options.numberOfGrids) classNumber = 1; overlay.addClass(options.classPrefix + classNumber); showOverlay(); if (/webkit/.test( navigator.userAgent.toLowerCase() )) { forceRepaint(); } saveState(); } break; } + + return true; } function keyupHandler(e) { - var m = getModifier(e); - if (!m) return true; - var k = getKey(e); - if (!k) return true; - if ((k == options.showGridKey) && !sticky) { + var k, + m = getModifier(e); + + if (!m) { + return true; + } + + k = getKey(e); + + if (k && (k == options.showGridKey) && !sticky) { overlay.hide(); overlayOn = false; } + + return true; } /** * Cookie functions * * By Peter-Paul Koch: * http://www.quirksmode.org/js/cookies.html */ - function createCookie(name,value,days) { + function createCookie(name, value, days) { + var date, + expires = ""; + if (days) { - var date = new Date(); - date.setTime(date.getTime()+(days*24*60*60*1000)); - var expires = "; expires="+date.toGMTString(); + date = new Date(); + date.setTime( date.getTime() + (days*24*60*60*1000) ); + expires = "; expires=" + date.toGMTString(); } - else var expires = ""; - document.cookie = name+"="+value+expires+"; path=/"; + + document.cookie = name + "=" + value + expires + "; path=/"; } function readCookie(name) { - var nameEQ = name + "="; - var ca = document.cookie.split(';'); - for(var i=0;i < ca.length;i++) { - var c = ca[i]; - while (c.charAt(0)==' ') c = c.substring(1,c.length); - if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); + var c, + ca = document.cookie.split(';'), + i = 0, + len = ca.length, + nameEQ = name + "="; + + for (; i < len; i++) { + c = ca[i]; + + while (c.charAt(0) == ' ') { + c = c.substring(1, c.length); + } + + if (c.indexOf(nameEQ) == 0) { + return c.substring(nameEQ.length, c.length); + } } return null; } function eraseCookie(name) { - createCookie(name,"",-1); + createCookie(name, "", -1); } /** * Forces a repaint (because WebKit has issues) * http://www.sitepoint.com/forums/showthread.php?p=4538763 * http://www.phpied.com/the-new-game-show-will-it-reflow/ */ function forceRepaint() { var ss = document.styleSheets[0]; try { ss.addRule('.xxxxxx', 'position: relative'); ss.removeRule(ss.rules.length - 1); - } catch(e){} + } catch(e) {} } -} + return {}; +}; /** * You can call hashgrid from your own code, but it's loaded here as * an example for your convenience. */ $(document).ready(function() { var grid = new hashgrid({ numberOfGrids: 2 }); });
dotjay/hashgrid
7a1e5b9ec6ad705f8845aa76cd874c4cb315837c
making the appending of grid lines and vert bars not query the DOM every iteration for the loops they are in. they should now only append to the DOM once after they have been added to a string.
diff --git a/hashgrid.js b/hashgrid.js index db7af79..0401521 100644 --- a/hashgrid.js +++ b/hashgrid.js @@ -1,340 +1,344 @@ /** * hashgrid (jQuery version) * http://github.com/dotjay/hashgrid * Version 5, 3 Nov 2010 * Written by Jon Gibbins, dotjay.co.uk, accessibility.co.uk * Contibutors: * Sean Coates, seancoates.com * Phil Dokas, jetless.org * * // Using a basic #grid setup * var grid = new hashgrid(); * * // Using #grid with a custom id (e.g. #mygrid) * var grid = new hashgrid("mygrid"); * * // Using #grid with additional options * var grid = new hashgrid({ * id: 'mygrid', // id for the grid container * modifierKey: 'alt', // optional 'ctrl', 'alt' or 'shift' * showGridKey: 's', // key to show the grid * holdGridKey: 'enter', // key to hold the grid in place * foregroundKey: 'f', // key to toggle foreground/background * jumpGridsKey: 'd', // key to cycle through the grid classes * numberOfGrids: 2, // number of grid classes used * classPrefix: 'class', // prefix for the grid classes * cookiePrefix: 'mygrid' // prefix for the cookie name * }); */ if (typeof jQuery == "undefined") { alert("Hashgrid: jQuery not loaded. Make sure it's linked to your pages."); } /** * hashgrid overlay */ var hashgrid = function(set) { var options = { id: 'grid', // id for the grid container modifierKey: null, // optional 'ctrl', 'alt' or 'shift' showGridKey: 'g', // key to show the grid holdGridKey: 'h', // key to hold the grid in place foregroundKey: 'f', // key to toggle foreground/background jumpGridsKey: 'j', // key to cycle through the grid classes numberOfGrids: 1, // number of grid classes used classPrefix: 'grid-', // prefix for the grid classes cookiePrefix: 'hashgrid'// prefix for the cookie name }; var overlayOn = false, sticky = false, overlayZState = 'B', overlayZBackground = -1, overlayZForeground = 9999, classNumber = 1; // Apply options if (typeof set == 'object') { var k; for (k in set) options[k] = set[k]; } else if (typeof set == 'string') { options.id = set; } // Remove any conflicting overlay if ($('#' + options.id).length > 0) { $('#' + options.id).remove(); } // Create overlay, hidden before adding to DOM var overlayEl = $('<div></div>'); overlayEl .attr('id', options.id) .css({ display: 'none', 'pointer-events': 'none' }); $("body").prepend(overlayEl); var overlay = $('#' + options.id); // Unless a custom z-index is set, ensure the overlay will be behind everything if (overlay.css('z-index') == 'auto') overlay.css('z-index', overlayZBackground); // Override the default overlay height with the actual page height var pageHeight = parseFloat($(document).height()); overlay.height(pageHeight); // Add the first grid line so that we can measure it overlay.append('<div id="' + options.id + '-horiz" class="horiz first-line">'); // Position off-screen and display to calculate height var top = overlay.css("top"); overlay.css({ top: "-999px", display: "block" }); // Calculate the number of grid lines needed var line = $('#' + options.id + '-horiz'), lineHeight = line.outerHeight(); // Hide and reset top overlay.css({ display: "none", top: top }); // Break on zero line height if (lineHeight <= 0) return true; // Add the remaining grid lines - var i, numGridLines = Math.floor(pageHeight / lineHeight); + var i, numGridLines = Math.floor(pageHeight / lineHeight), + gridLines = ''; for (i = numGridLines - 1; i >= 1; i--) { - overlay.append('<div class="horiz"></div>'); + gridLines += '<div class="horiz"></div>'; } + overlay.append(gridLines); // vertical grid overlay.append($('<div class="vert-container"></div>')); var overlayVert = overlay.children('.vert-container'); var gridWidth = overlay.width(); overlayVert.css({width: gridWidth, position: 'absolute', top: 0}); overlayVert.append('<div class="vert first-line">&nbsp;</div>'); // 30 is an arbitrarily large number... // can't calculate the margin width properly + var gridVert = ''; for (i = 0; i < 30; i++) { - overlayVert.append('<div class="vert">&nbsp;</div>'); + gridVert += '<div class="vert">&nbsp;</div>'; } + overlayVert.append(gridVert); overlayVert.children() .height(pageHeight) .css({display: 'inline-block'}); // Check for saved state var overlayCookie = readCookie(options.cookiePrefix + options.id); if (typeof overlayCookie == 'string') { var state = overlayCookie.split(','); state[2] = Number(state[2]); if ((typeof state[2] == 'number') && !isNaN(state[2])) { classNumber = state[2].toFixed(0); overlay.addClass(options.classPrefix + classNumber); } if (state[1] == 'F') { overlayZState = 'F'; overlay.css('z-index', overlayZForeground); } if (state[0] == '1') { overlayOn = true; sticky = true; showOverlay(); } } else { overlay.addClass(options.classPrefix + classNumber); } // Keyboard controls $(document).bind('keydown', keydownHandler); $(document).bind('keyup', keyupHandler); /** * Helpers */ function getModifier(e) { if (options.modifierKey == null) return true; // Bypass by default var m = true; switch(options.modifierKey) { case 'ctrl': m = (e.ctrlKey ? e.ctrlKey : false); break; case 'alt': m = (e.altKey ? e.altKey : false); break; case 'shift': m = (e.shiftKey ? e.shiftKey : false); break; } return m; } function getKey(e) { var k = false, c = (e.keyCode ? e.keyCode : e.which); // Handle keywords if (c == 13) k = 'enter'; // Handle letters else k = String.fromCharCode(c).toLowerCase(); return k; } function saveState() { createCookie(options.cookiePrefix + options.id, (sticky ? '1' : '0') + ',' + overlayZState + ',' + classNumber, 1); } function showOverlay() { overlay.show(); overlayVert.css({width: overlay.width()}); // hide any vertical blocks that aren't at the top of the viewport overlayVert.children('.vert').each(function () { $(this).css('display','inline-block'); if ($(this).offset().top > 0) { $(this).hide(); } }); } /** * Event handlers */ function keydownHandler(e) { var source = e.target.tagName.toLowerCase(); if ((source == 'input') || (source == 'textarea') || (source == 'select')) return true; var m = getModifier(e); if (!m) return true; var k = getKey(e); if (!k) return true; switch(k) { case options.showGridKey: if (!overlayOn) { showOverlay(); overlayOn = true; } else if (sticky) { overlay.hide(); overlayOn = false; sticky = false; saveState(); } break; case options.holdGridKey: if (overlayOn && !sticky) { // Turn sticky overlay on sticky = true; saveState(); } break; case options.foregroundKey: if (overlayOn) { // Toggle sticky overlay z-index if (overlay.css('z-index') == overlayZForeground) { overlay.css('z-index', overlayZBackground); overlayZState = 'B'; } else { overlay.css('z-index', overlayZForeground); overlayZState = 'F'; } saveState(); } break; case options.jumpGridsKey: if (overlayOn && (options.numberOfGrids > 1)) { // Cycle through the available grids overlay.removeClass(options.classPrefix + classNumber); classNumber++; if (classNumber > options.numberOfGrids) classNumber = 1; overlay.addClass(options.classPrefix + classNumber); showOverlay(); if (/webkit/.test( navigator.userAgent.toLowerCase() )) { forceRepaint(); } saveState(); } break; } } function keyupHandler(e) { var m = getModifier(e); if (!m) return true; var k = getKey(e); if (!k) return true; if ((k == options.showGridKey) && !sticky) { overlay.hide(); overlayOn = false; } } /** * Cookie functions * * By Peter-Paul Koch: * http://www.quirksmode.org/js/cookies.html */ function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function eraseCookie(name) { createCookie(name,"",-1); } /** * Forces a repaint (because WebKit has issues) * http://www.sitepoint.com/forums/showthread.php?p=4538763 * http://www.phpied.com/the-new-game-show-will-it-reflow/ */ function forceRepaint() { var ss = document.styleSheets[0]; try { ss.addRule('.xxxxxx', 'position: relative'); ss.removeRule(ss.rules.length - 1); } catch(e){} } } /** * You can call hashgrid from your own code, but it's loaded here as * an example for your convenience. */ $(document).ready(function() { var grid = new hashgrid({ numberOfGrids: 2 }); });
dotjay/hashgrid
722bb0e1152fbb9af6c57cae1cc940414c473c56
Updating documentation to reflect present state of pointer-events implementation. Tested against mentioned browsers, plus Opera 10.10, 10.63, 11 alpha (all show the odd behavior of allowing text selection but not truly passing pointer events through to underlying elements), MSIE 8, 9 beta (PP6 appears unchanged -- http://msdn.microsoft.com/en-us/ie/ff468705.aspx).
diff --git a/index.htm b/index.htm index e42eb4c..29c5a67 100644 --- a/index.htm +++ b/index.htm @@ -1,427 +1,427 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>#grid</title> <style type="text/css"> /* Putting inline rules here so the document can be downloaded with style */ body{ font-size: 1em; line-height: 1.25; font-family: Arial, sans-serif; background: White; color: DimGray; margin: 0; padding: 0 20px; } #content{ font-size: 16px; line-height: 20px; position: relative; } #content{ width: 620px; margin: 0 auto; } #footer{ border-top: 1px dotted DarkGray; padding-top: 19px; } h1, h2{ color: Black; font-weight: normal; } h1{ font-size: 36px; line-height: 40px; margin: 40px 0 20px; padding-bottom: 19px; border-bottom: 1px dotted DarkGray; } h1 em{ font-style: normal; color: DarkGray; font-size: 16px; line-height: 20px; margin: 0 0 20px; } h2, h3{ font-size: 16px; font-weight: 700; line-height: 20px; margin: 0 0 20px; } h3{ font-weight: 300; } a:link, a:visited{ color: Black; text-decoration: none; padding: 0 2px; background-color: WhiteSmoke; border-bottom: 1px solid Gold; } a:focus{ outline: none; } a:focus, a:hover, a:active{ background-color: Khaki; border-bottom: 1px solid GoldenRod; } p, ul{ padding: 0; margin: 0 0 20px; } dl, ol{ padding: 0; margin: 0; } ul{ list-style: circle; } ol li{ margin-bottom: 20px; } dd{ margin: 0 0 20px 0; } del{ text-decoration: line-through; opacity: 0.75; } ins{ text-decoration: none; } code{ font-size: 14px; line-height: 1; } textarea{ font-family: 'Courier New', monospace; font-size: 14px; line-height: 20px; display: block; width: 600px; margin: 0 0 20px; padding: 0 0 0 15px; border: 0; color: Black; background: Gainsboro; border-left: 5px solid DarkGray; } #javascript-code{ height: 180px; } #css-code{ height: 1300px; } .summary em{ font-style: normal; position: absolute; color: DarkGray; right: 0; top: 18px; width: 140px; } .summary em span{ position: absolute; left: -9999px; } #download{ line-height: 60px; padding: 0 40px 0 15px; border-left: 5px solid DarkGray; background: Gainsboro; color: DimGray; } span.key{ color: Black; text-transform: uppercase; } </style> <!-- Set styles --> <style type="text/css"> /** * Grid */ #grid{ /* Dimensions - same width as your grid with gutters */ width: 980px; /* Grid (left-aligned) position: absolute; top: 0; left: 0; */ /* Grid (centered) */ position: absolute; top: 0; left: 50%; margin-left: -490px; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ #grid div.vert{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-right: 19px; } #grid div.vert.first-line{ margin-left: 19px; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ #grid div.horiz{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option in the hashgrid.js file. */ #grid.grid-1 div.vert{ /* Vertical grid line colour for grid 1 */ border-color: darkturquoise; } #grid.grid-2{ /* Adjustments */ padding: 0 160px; width: 660px; } #grid.grid-2 div.vert{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </style> </head> <body> <div id="content" role="main"> <h1>#grid <em>v5</em></h1> <p class="summary"><em>Wed, 3 Nov 2010<span>:</span></em> This is a little tool we created for our <a href="http://analog.coop/">Analog&#160;holding&#160;page</a>. It inserts a <a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a> in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit <span class="key">G</span> on your keyboard.</p> <h2>Download</h2> <p id="download"><a href="http://github.com/dotjay/hashgrid/downloads">Download #grid</a> from <a href="http://github.com/dotjay/hashgrid">GitHub</a></p> <h2 id="features">Features</h2> <ul> <li>Adaptable for all layout widths and alignments</li> <li>Adaptable for any vertical rhythm value</li> <li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li> <li>Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters</li> </ul> <p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p> <h2 id="installation">Installation</h2> <ol> <li><h3>Copy the <a href="http://github.com/dotjay/hashgrid/blob/v5/hashgrid.js">hashgrid.js</a> script to your project</h3></li> <li><h3>Add the script to your page(s) just inside the <code>&#60;/body&#62;</code> tag</h3> <textarea id="javascript-code" cols="68" rows="8" readonly="readonly"> &#60;!-- Grab latest version of jQuery --&#62; &#60;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"&#62; &#60;/script&#62; &#60;!-- Include the hashgrid script --&#62; &#60;script type="text/javascript" src="hashgrid.js"&#62;&#60;/script&#62;</textarea></li> <li><h3>Add the CSS to your page(s)</h3> <textarea id="css-code" cols="68" rows="64" readonly="readonly"> /** * Grid */ #grid{ /* Dimensions - same width as your grid with gutters */ width: 980px; /* Grid (left-aligned) position: absolute; top: 0; left: 0; */ /* Grid (centered) */ position: absolute; top: 0; left: 50%; margin-left: -490px; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ #grid div.vert{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-right: 19px; } #grid div.vert.first-line{ margin-left: 19px; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ #grid div.horiz{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option in the hashgrid.js file. */ #grid.grid-1 div.vert{ /* Vertical grid line colour for grid 1 */ border-color: darkturquoise; } #grid.grid-2{ /* Adjustments */ padding: 0 160px; width: 660px; } #grid.grid-2 div.vert{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </textarea></li> <li><h3>Modify #grid to suit your needs</h3> <p>The CSS and JavaScript is annotated to help you.</p></li> </ol> <h2 id="usage">Usage</h2> <p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p> <dl> <dt><span class="key">G</span></dt> <dd>Show the grid until you release.</dd> <dt><span class="key">G</span> + <span class="key">H</span></dt> <dd>Show and hold the grid (<span class="key">G</span> will remove it again).</dd> <dt><span class="key">G</span> + <span class="key">F</span></dt> <dd>Toggle the grid to the foreground and back. Pressing <span class="key">F</span> while the grid is held also works.</dd> <dt><span class="key">G</span> + <span class="key">J</span></dt> <dd>Jump to the next grid. Pressing <span class="key">J</span> while the grid is held also works.</dd> </dl> -<p><em>N.B. A cookie conveniently remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em></p> +<p><em>N.B. A cookie conveniently remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page except in Chrome v4, Safari v4, Firefox v3.6, or more recent versions.</em></p> <h2 id="release-notes">Release Notes</h2> <dl> <dt>v5&#8201;&#8212;&#8201;3 Nov 2010</dt> <dd> <ul> <li>Vertical grid lines can now be set using CSS&#8230; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution.</li> <li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li> <li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback.</li> </ul> </dd> <dt>v4&#8201;&#8212;&#8201;29 Mar 2010</dt> <dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd> <dt>v3&#8201;&#8212;&#8201;22 Feb 2010</dt> <dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd> <dt>v2&#8201;&#8212;&#8201;2 Feb 2010</dt> <dd>Keys are now more easily configured (see top of hashgrid.js). Renamed the GridOverlay object to hashgrid. Fixed crash when using with disabled CSS.</dd> <dt>v1&#8201;&#8212;&#8201;21 Dec 2009</dt> <dd>First release.</dd> </dl> <h2 id="known-issues">Known Issues</h2> <ul> <li><del>IE 8: Fully functional, but the default <span class="key">ALT</span> + <span class="key">G</span> + <span class="key">ENTER</span> shortcut puts IE into full screen mode. Hit <span class="key">ALT</span> + <span class="key">ENTER</span> to toggle full screen mode off again.</del><ins datetime="2010-02-22"> The default keyboard shortcuts have been changed.</ins></li> <li>IE 6: The grid is always in the foreground.</li> <li>Opera 9/10: Using <span class="key">CTRL</span> or <span class="key">ALT</span> as a modifier key will not work due to different key handling by the browser.</li> </ul> <h2 id="license">License</h2> <p>Released under a <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike License</a>, which essentially means that you&#8217;re free to copy it and adapt it. <a href="http://analog.coop/#talk-to-us">Contact us at Analog</a> if you need a different license.</p> <div id="footer" role="contentinfo"> <p>#grid is an <a href="http://analog.coop/">Analog</a> gig. It was conceived by <a href="http://jontangerine.com/">Jon Tan</a>, and built by <a href="http://accessibility.co.uk/">Jon Gibbins</a>, in cahoots with our <a href="http://analog.coop#is">fine friends</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p> </div> </div> <!-- Grab latest version of jQuery --> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <!-- Include the hashgrid script --> <script type="text/javascript" src="hashgrid.js"></script> </body> </html>
dotjay/hashgrid
fc0c4489f61cacb99aa3ac1b6685507907d2700f
Updating documention for version 5.
diff --git a/index.htm b/index.htm index 25ceef7..e42eb4c 100644 --- a/index.htm +++ b/index.htm @@ -1,427 +1,427 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>#grid</title> <style type="text/css"> /* Putting inline rules here so the document can be downloaded with style */ body{ font-size: 1em; line-height: 1.25; font-family: Arial, sans-serif; background: White; color: DimGray; margin: 0; padding: 0 20px; } #content{ font-size: 16px; line-height: 20px; position: relative; } #content{ width: 620px; margin: 0 auto; } #footer{ border-top: 1px dotted DarkGray; padding-top: 19px; } h1, h2{ color: Black; font-weight: normal; } h1{ font-size: 36px; line-height: 40px; margin: 40px 0 20px; padding-bottom: 19px; border-bottom: 1px dotted DarkGray; } h1 em{ font-style: normal; color: DarkGray; font-size: 16px; line-height: 20px; margin: 0 0 20px; } h2, h3{ font-size: 16px; font-weight: 700; line-height: 20px; margin: 0 0 20px; } h3{ font-weight: 300; } a:link, a:visited{ color: Black; text-decoration: none; padding: 0 2px; background-color: WhiteSmoke; border-bottom: 1px solid Gold; } a:focus{ outline: none; } a:focus, a:hover, a:active{ background-color: Khaki; border-bottom: 1px solid GoldenRod; } p, ul{ padding: 0; margin: 0 0 20px; } dl, ol{ padding: 0; margin: 0; } ul{ list-style: circle; } ol li{ margin-bottom: 20px; } dd{ margin: 0 0 20px 0; } del{ text-decoration: line-through; opacity: 0.75; } ins{ text-decoration: none; } code{ font-size: 14px; line-height: 1; } textarea{ font-family: 'Courier New', monospace; font-size: 14px; line-height: 20px; display: block; width: 600px; margin: 0 0 20px; padding: 0 0 0 15px; border: 0; color: Black; background: Gainsboro; border-left: 5px solid DarkGray; } #javascript-code{ height: 180px; } #css-code{ height: 1300px; } .summary em{ font-style: normal; position: absolute; color: DarkGray; right: 0; top: 18px; width: 140px; } .summary em span{ position: absolute; left: -9999px; } #download{ line-height: 60px; padding: 0 40px 0 15px; border-left: 5px solid DarkGray; background: Gainsboro; color: DimGray; } span.key{ color: Black; text-transform: uppercase; } </style> <!-- Set styles --> <style type="text/css"> /** * Grid */ #grid{ /* Dimensions - same width as your grid with gutters */ width: 980px; /* Grid (left-aligned) position: absolute; top: 0; left: 0; */ /* Grid (centered) */ position: absolute; top: 0; left: 50%; margin-left: -490px; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ #grid div.vert{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-right: 19px; } #grid div.vert.first-line{ margin-left: 19px; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ #grid div.horiz{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option in the hashgrid.js file. */ #grid.grid-1 div.vert{ /* Vertical grid line colour for grid 1 */ border-color: darkturquoise; } #grid.grid-2{ /* Adjustments */ padding: 0 160px; width: 660px; } #grid.grid-2 div.vert{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </style> </head> <body> <div id="content" role="main"> <h1>#grid <em>v5</em></h1> <p class="summary"><em>Wed, 3 Nov 2010<span>:</span></em> This is a little tool we created for our <a href="http://analog.coop/">Analog&#160;holding&#160;page</a>. It inserts a <a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a> in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit <span class="key">G</span> on your keyboard.</p> <h2>Download</h2> <p id="download"><a href="http://github.com/dotjay/hashgrid/downloads">Download #grid</a> from <a href="http://github.com/dotjay/hashgrid">GitHub</a></p> <h2 id="features">Features</h2> <ul> <li>Adaptable for all layout widths and alignments</li> <li>Adaptable for any vertical rhythm value</li> <li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li> <li>Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters</li> </ul> <p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p> <h2 id="installation">Installation</h2> <ol> <li><h3>Copy the <a href="http://github.com/dotjay/hashgrid/blob/v5/hashgrid.js">hashgrid.js</a> script to your project</h3></li> <li><h3>Add the script to your page(s) just inside the <code>&#60;/body&#62;</code> tag</h3> <textarea id="javascript-code" cols="68" rows="8" readonly="readonly"> &#60;!-- Grab latest version of jQuery --&#62; &#60;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"&#62; &#60;/script&#62; &#60;!-- Include the hashgrid script --&#62; &#60;script type="text/javascript" src="hashgrid.js"&#62;&#60;/script&#62;</textarea></li> <li><h3>Add the CSS to your page(s)</h3> <textarea id="css-code" cols="68" rows="64" readonly="readonly"> /** * Grid */ #grid{ /* Dimensions - same width as your grid with gutters */ width: 980px; /* Grid (left-aligned) position: absolute; top: 0; left: 0; */ /* Grid (centered) */ position: absolute; top: 0; left: 50%; margin-left: -490px; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ #grid div.vert{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-right: 19px; } #grid div.vert.first-line{ margin-left: 19px; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ #grid div.horiz{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option in the hashgrid.js file. */ #grid.grid-1 div.vert{ /* Vertical grid line colour for grid 1 */ border-color: darkturquoise; } #grid.grid-2{ /* Adjustments */ padding: 0 160px; width: 660px; } #grid.grid-2 div.vert{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </textarea></li> <li><h3>Modify #grid to suit your needs</h3> <p>The CSS and JavaScript is annotated to help you.</p></li> </ol> <h2 id="usage">Usage</h2> <p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p> <dl> <dt><span class="key">G</span></dt> <dd>Show the grid until you release.</dd> <dt><span class="key">G</span> + <span class="key">H</span></dt> <dd>Show and hold the grid (<span class="key">G</span> will remove it again).</dd> <dt><span class="key">G</span> + <span class="key">F</span></dt> <dd>Toggle the grid to the foreground and back. Pressing <span class="key">F</span> while the grid is held also works.</dd> <dt><span class="key">G</span> + <span class="key">J</span></dt> <dd>Jump to the next grid. Pressing <span class="key">J</span> while the grid is held also works.</dd> </dl> <p><em>N.B. A cookie conveniently remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em></p> <h2 id="release-notes">Release Notes</h2> <dl> <dt>v5&#8201;&#8212;&#8201;3 Nov 2010</dt> <dd> <ul> -<li>Vertical grid lines can now be set using CSS&#8212; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution.</li> +<li>Vertical grid lines can now be set using CSS&#8230; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution.</li> <li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li> <li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback.</li> </ul> </dd> <dt>v4&#8201;&#8212;&#8201;29 Mar 2010</dt> <dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd> <dt>v3&#8201;&#8212;&#8201;22 Feb 2010</dt> <dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd> <dt>v2&#8201;&#8212;&#8201;2 Feb 2010</dt> <dd>Keys are now more easily configured (see top of hashgrid.js). Renamed the GridOverlay object to hashgrid. Fixed crash when using with disabled CSS.</dd> <dt>v1&#8201;&#8212;&#8201;21 Dec 2009</dt> <dd>First release.</dd> </dl> <h2 id="known-issues">Known Issues</h2> <ul> <li><del>IE 8: Fully functional, but the default <span class="key">ALT</span> + <span class="key">G</span> + <span class="key">ENTER</span> shortcut puts IE into full screen mode. Hit <span class="key">ALT</span> + <span class="key">ENTER</span> to toggle full screen mode off again.</del><ins datetime="2010-02-22"> The default keyboard shortcuts have been changed.</ins></li> <li>IE 6: The grid is always in the foreground.</li> <li>Opera 9/10: Using <span class="key">CTRL</span> or <span class="key">ALT</span> as a modifier key will not work due to different key handling by the browser.</li> </ul> <h2 id="license">License</h2> <p>Released under a <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike License</a>, which essentially means that you&#8217;re free to copy it and adapt it. <a href="http://analog.coop/#talk-to-us">Contact us at Analog</a> if you need a different license.</p> <div id="footer" role="contentinfo"> <p>#grid is an <a href="http://analog.coop/">Analog</a> gig. It was conceived by <a href="http://jontangerine.com/">Jon Tan</a>, and built by <a href="http://accessibility.co.uk/">Jon Gibbins</a>, in cahoots with our <a href="http://analog.coop#is">fine friends</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p> </div> </div> <!-- Grab latest version of jQuery --> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <!-- Include the hashgrid script --> <script type="text/javascript" src="hashgrid.js"></script> </body> </html>
dotjay/hashgrid
3dbcf4e835af579acb5e1446c9393e6f7755ddf1
Link to version 5 download on github
diff --git a/index.htm b/index.htm index e3ac174..25ceef7 100644 --- a/index.htm +++ b/index.htm @@ -1,427 +1,427 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>#grid</title> <style type="text/css"> /* Putting inline rules here so the document can be downloaded with style */ body{ font-size: 1em; line-height: 1.25; font-family: Arial, sans-serif; background: White; color: DimGray; margin: 0; padding: 0 20px; } #content{ font-size: 16px; line-height: 20px; position: relative; } #content{ width: 620px; margin: 0 auto; } #footer{ border-top: 1px dotted DarkGray; padding-top: 19px; } h1, h2{ color: Black; font-weight: normal; } h1{ font-size: 36px; line-height: 40px; margin: 40px 0 20px; padding-bottom: 19px; border-bottom: 1px dotted DarkGray; } h1 em{ font-style: normal; color: DarkGray; font-size: 16px; line-height: 20px; margin: 0 0 20px; } h2, h3{ font-size: 16px; font-weight: 700; line-height: 20px; margin: 0 0 20px; } h3{ font-weight: 300; } a:link, a:visited{ color: Black; text-decoration: none; padding: 0 2px; background-color: WhiteSmoke; border-bottom: 1px solid Gold; } a:focus{ outline: none; } a:focus, a:hover, a:active{ background-color: Khaki; border-bottom: 1px solid GoldenRod; } p, ul{ padding: 0; margin: 0 0 20px; } dl, ol{ padding: 0; margin: 0; } ul{ list-style: circle; } ol li{ margin-bottom: 20px; } dd{ margin: 0 0 20px 0; } del{ text-decoration: line-through; opacity: 0.75; } ins{ text-decoration: none; } code{ font-size: 14px; line-height: 1; } textarea{ font-family: 'Courier New', monospace; font-size: 14px; line-height: 20px; display: block; width: 600px; margin: 0 0 20px; padding: 0 0 0 15px; border: 0; color: Black; background: Gainsboro; border-left: 5px solid DarkGray; } #javascript-code{ height: 180px; } #css-code{ height: 1300px; } .summary em{ font-style: normal; position: absolute; color: DarkGray; right: 0; top: 18px; width: 140px; } .summary em span{ position: absolute; left: -9999px; } #download{ line-height: 60px; padding: 0 40px 0 15px; border-left: 5px solid DarkGray; background: Gainsboro; color: DimGray; } span.key{ color: Black; text-transform: uppercase; } </style> <!-- Set styles --> <style type="text/css"> /** * Grid */ #grid{ /* Dimensions - same width as your grid with gutters */ width: 980px; /* Grid (left-aligned) position: absolute; top: 0; left: 0; */ /* Grid (centered) */ position: absolute; top: 0; left: 50%; margin-left: -490px; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ #grid div.vert{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-right: 19px; } #grid div.vert.first-line{ margin-left: 19px; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ #grid div.horiz{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option in the hashgrid.js file. */ #grid.grid-1 div.vert{ /* Vertical grid line colour for grid 1 */ border-color: darkturquoise; } #grid.grid-2{ /* Adjustments */ padding: 0 160px; width: 660px; } #grid.grid-2 div.vert{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </style> </head> <body> <div id="content" role="main"> <h1>#grid <em>v5</em></h1> <p class="summary"><em>Wed, 3 Nov 2010<span>:</span></em> This is a little tool we created for our <a href="http://analog.coop/">Analog&#160;holding&#160;page</a>. It inserts a <a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a> in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit <span class="key">G</span> on your keyboard.</p> <h2>Download</h2> <p id="download"><a href="http://github.com/dotjay/hashgrid/downloads">Download #grid</a> from <a href="http://github.com/dotjay/hashgrid">GitHub</a></p> <h2 id="features">Features</h2> <ul> <li>Adaptable for all layout widths and alignments</li> <li>Adaptable for any vertical rhythm value</li> <li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li> <li>Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters</li> </ul> <p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p> <h2 id="installation">Installation</h2> <ol> -<li><h3>Copy the <a href="http://github.com/dotjay/hashgrid/blob/v4/hashgrid.js">hashgrid.js</a> script to your project</h3></li> +<li><h3>Copy the <a href="http://github.com/dotjay/hashgrid/blob/v5/hashgrid.js">hashgrid.js</a> script to your project</h3></li> <li><h3>Add the script to your page(s) just inside the <code>&#60;/body&#62;</code> tag</h3> <textarea id="javascript-code" cols="68" rows="8" readonly="readonly"> &#60;!-- Grab latest version of jQuery --&#62; &#60;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"&#62; &#60;/script&#62; &#60;!-- Include the hashgrid script --&#62; &#60;script type="text/javascript" src="hashgrid.js"&#62;&#60;/script&#62;</textarea></li> <li><h3>Add the CSS to your page(s)</h3> <textarea id="css-code" cols="68" rows="64" readonly="readonly"> /** * Grid */ #grid{ /* Dimensions - same width as your grid with gutters */ width: 980px; /* Grid (left-aligned) position: absolute; top: 0; left: 0; */ /* Grid (centered) */ position: absolute; top: 0; left: 50%; margin-left: -490px; } /** * Vertical grid lines * * Set the column width taking the borders into consideration, * and use margins to set column gutters. */ #grid div.vert{ width: 139px; border: solid darkturquoise; border-width: 0 1px; margin-right: 19px; } #grid div.vert.first-line{ margin-left: 19px; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ #grid div.horiz{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option in the hashgrid.js file. */ #grid.grid-1 div.vert{ /* Vertical grid line colour for grid 1 */ border-color: darkturquoise; } #grid.grid-2{ /* Adjustments */ padding: 0 160px; width: 660px; } #grid.grid-2 div.vert{ /* Vertical grid line colour for grid 2 */ border-color: crimson; } </textarea></li> <li><h3>Modify #grid to suit your needs</h3> <p>The CSS and JavaScript is annotated to help you.</p></li> </ol> <h2 id="usage">Usage</h2> <p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p> <dl> <dt><span class="key">G</span></dt> <dd>Show the grid until you release.</dd> <dt><span class="key">G</span> + <span class="key">H</span></dt> <dd>Show and hold the grid (<span class="key">G</span> will remove it again).</dd> <dt><span class="key">G</span> + <span class="key">F</span></dt> <dd>Toggle the grid to the foreground and back. Pressing <span class="key">F</span> while the grid is held also works.</dd> <dt><span class="key">G</span> + <span class="key">J</span></dt> <dd>Jump to the next grid. Pressing <span class="key">J</span> while the grid is held also works.</dd> </dl> <p><em>N.B. A cookie conveniently remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em></p> <h2 id="release-notes">Release Notes</h2> <dl> <dt>v5&#8201;&#8212;&#8201;3 Nov 2010</dt> <dd> <ul> <li>Vertical grid lines can now be set using CSS&#8212; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution.</li> <li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li> <li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback.</li> </ul> </dd> <dt>v4&#8201;&#8212;&#8201;29 Mar 2010</dt> <dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd> <dt>v3&#8201;&#8212;&#8201;22 Feb 2010</dt> <dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd> <dt>v2&#8201;&#8212;&#8201;2 Feb 2010</dt> <dd>Keys are now more easily configured (see top of hashgrid.js). Renamed the GridOverlay object to hashgrid. Fixed crash when using with disabled CSS.</dd> <dt>v1&#8201;&#8212;&#8201;21 Dec 2009</dt> <dd>First release.</dd> </dl> <h2 id="known-issues">Known Issues</h2> <ul> <li><del>IE 8: Fully functional, but the default <span class="key">ALT</span> + <span class="key">G</span> + <span class="key">ENTER</span> shortcut puts IE into full screen mode. Hit <span class="key">ALT</span> + <span class="key">ENTER</span> to toggle full screen mode off again.</del><ins datetime="2010-02-22"> The default keyboard shortcuts have been changed.</ins></li> <li>IE 6: The grid is always in the foreground.</li> <li>Opera 9/10: Using <span class="key">CTRL</span> or <span class="key">ALT</span> as a modifier key will not work due to different key handling by the browser.</li> </ul> <h2 id="license">License</h2> <p>Released under a <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike License</a>, which essentially means that you&#8217;re free to copy it and adapt it. <a href="http://analog.coop/#talk-to-us">Contact us at Analog</a> if you need a different license.</p> <div id="footer" role="contentinfo"> <p>#grid is an <a href="http://analog.coop/">Analog</a> gig. It was conceived by <a href="http://jontangerine.com/">Jon Tan</a>, and built by <a href="http://accessibility.co.uk/">Jon Gibbins</a>, in cahoots with our <a href="http://analog.coop#is">fine friends</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p> </div> </div> <!-- Grab latest version of jQuery --> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <!-- Include the hashgrid script --> <script type="text/javascript" src="hashgrid.js"></script> </body> </html>
dotjay/hashgrid
c09d1e05eed1bbd814974c11bd4422088d42ddea
Updating documention for version 5.
diff --git a/README.md b/README.md index c4326c7..800e550 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,14 @@ #grid ===== A little tool that inserts a layout grid in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. Features -------- * Adaptable for all layout widths and alignments * Adaptable for any vertical rhythm value * Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids - * Uses a single JavaScript file, and a little CSS + * Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters Notes on installation and usage can be found in the included index.htm file.
dotjay/hashgrid
e35cd485288cf837e2e73623e49fc6196d4c62eb
Adjusting CSS for version 5, and updating documention.
diff --git a/index.htm b/index.htm index b88344c..e3ac174 100644 --- a/index.htm +++ b/index.htm @@ -1,388 +1,427 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>#grid</title> <style type="text/css"> /* Putting inline rules here so the document can be downloaded with style */ body{ font-size: 1em; line-height: 1.25; font-family: Arial, sans-serif; background: White; color: DimGray; margin: 0; padding: 0 20px; } #content{ font-size: 16px; line-height: 20px; position: relative; } #content{ width: 620px; margin: 0 auto; } #footer{ border-top: 1px dotted DarkGray; padding-top: 19px; } h1, h2{ color: Black; font-weight: normal; } h1{ font-size: 36px; line-height: 40px; margin: 40px 0 20px; padding-bottom: 19px; border-bottom: 1px dotted DarkGray; } h1 em{ font-style: normal; color: DarkGray; font-size: 16px; line-height: 20px; margin: 0 0 20px; } h2, h3{ font-size: 16px; font-weight: 700; line-height: 20px; margin: 0 0 20px; } h3{ font-weight: 300; } a:link, a:visited{ color: Black; text-decoration: none; padding: 0 2px; background-color: WhiteSmoke; border-bottom: 1px solid Gold; } a:focus{ outline: none; } a:focus, a:hover, a:active{ background-color: Khaki; border-bottom: 1px solid GoldenRod; } p, ul{ padding: 0; margin: 0 0 20px; } dl, ol{ padding: 0; margin: 0; } ul{ list-style: circle; } ol li{ margin-bottom: 20px; } dd{ margin: 0 0 20px 0; } del{ text-decoration: line-through; opacity: 0.75; } ins{ text-decoration: none; } code{ font-size: 14px; line-height: 1; } textarea{ font-family: 'Courier New', monospace; font-size: 14px; line-height: 20px; display: block; width: 600px; margin: 0 0 20px; padding: 0 0 0 15px; border: 0; color: Black; background: Gainsboro; border-left: 5px solid DarkGray; } #javascript-code{ height: 180px; } #css-code{ height: 1300px; } .summary em{ font-style: normal; position: absolute; color: DarkGray; right: 0; top: 18px; width: 140px; } .summary em span{ position: absolute; left: -9999px; } #download{ line-height: 60px; padding: 0 40px 0 15px; border-left: 5px solid DarkGray; background: Gainsboro; color: DimGray; } span.key{ color: Black; text-transform: uppercase; } </style> <!-- Set styles --> <style type="text/css"> /** * Grid */ #grid{ /* Dimensions - same width as your grid with gutters */ width: 980px; /* Grid (left-aligned) position: absolute; top: 0; left: 0; */ /* Grid (centered) */ position: absolute; top: 0; left: 50%; margin-left: -490px; } /** - * Classes for vertical grids + * Vertical grid lines + * + * Set the column width taking the borders into consideration, + * and use margins to set column gutters. */ -#grid div.vert { - margin-right: 20px; - width: 138px; - border: 1px dashed darkgray; +#grid div.vert{ + + width: 139px; + border: solid darkturquoise; border-width: 0 1px; -} + margin-right: 19px; -#grid div.vert.first-line { - margin-left: 20px; } -/** -* Classes for multiple grids -* -* When using more than one grid, remember to set the numberOfGrids -* option in the hashgrid.js file. -*/ -#grid.grid-1 div.vert { - border-color: green; -} -#grid.grid-2 div.vert { - border-color: red; -} -#grid.grid-2 { - /* Adjustments */ - padding: 0 160px; - width: 660px; +#grid div.vert.first-line{ + + margin-left: 19px; + } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ #grid div.horiz{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; } +/** +* Classes for multiple grids +* +* When using more than one grid, remember to set the numberOfGrids +* option in the hashgrid.js file. +*/ +#grid.grid-1 div.vert{ + + /* Vertical grid line colour for grid 1 */ + border-color: darkturquoise; + +} +#grid.grid-2{ + + /* Adjustments */ + padding: 0 160px; + width: 660px; + +} +#grid.grid-2 div.vert{ + + /* Vertical grid line colour for grid 2 */ + border-color: crimson; + +} + </style> </head> <body> <div id="content" role="main"> -<h1>#grid <em>v4</em></h1> +<h1>#grid <em>v5</em></h1> -<p class="summary"><em>Mon, 29 Mar 2010<span>:</span></em> This is a little tool we created for our <a href="http://analog.coop/">Analog&#160;holding&#160;page</a>. It inserts a <a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a> in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit <span class="key">G</span> on your keyboard.</p> +<p class="summary"><em>Wed, 3 Nov 2010<span>:</span></em> This is a little tool we created for our <a href="http://analog.coop/">Analog&#160;holding&#160;page</a>. It inserts a <a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a> in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit <span class="key">G</span> on your keyboard.</p> <h2>Download</h2> <p id="download"><a href="http://github.com/dotjay/hashgrid/downloads">Download #grid</a> from <a href="http://github.com/dotjay/hashgrid">GitHub</a></p> <h2 id="features">Features</h2> <ul> <li>Adaptable for all layout widths and alignments</li> <li>Adaptable for any vertical rhythm value</li> <li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li> -<li>Uses a single JavaScript file, a little CSS</li> +<li>Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters</li> </ul> <p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p> <h2 id="installation">Installation</h2> <ol> <li><h3>Copy the <a href="http://github.com/dotjay/hashgrid/blob/v4/hashgrid.js">hashgrid.js</a> script to your project</h3></li> <li><h3>Add the script to your page(s) just inside the <code>&#60;/body&#62;</code> tag</h3> <textarea id="javascript-code" cols="68" rows="8" readonly="readonly"> &#60;!-- Grab latest version of jQuery --&#62; &#60;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"&#62; &#60;/script&#62; &#60;!-- Include the hashgrid script --&#62; &#60;script type="text/javascript" src="hashgrid.js"&#62;&#60;/script&#62;</textarea></li> <li><h3>Add the CSS to your page(s)</h3> <textarea id="css-code" cols="68" rows="64" readonly="readonly"> /** * Grid */ #grid{ /* Dimensions - same width as your grid with gutters */ width: 980px; /* Grid (left-aligned) position: absolute; top: 0; left: 0; */ /* Grid (centered) */ position: absolute; top: 0; left: 50%; margin-left: -490px; } /** - * Classes for vertical grids + * Vertical grid lines + * + * Set the column width taking the borders into consideration, + * and use margins to set column gutters. */ -#grid div.vert { - margin-right: 20px; - width: 138px; - border: 1px dashed darkgray; +#grid div.vert{ + + width: 139px; + border: solid darkturquoise; border-width: 0 1px; -} + margin-right: 19px; -#grid div.vert.first-line { - margin-left: 20px; } -/** -* Classes for multiple grids -* -* When using more than one grid, remember to set the numberOfGrids -* option in the hashgrid.js file. -*/ -#grid.grid-1 div.vert { - border-color: green; -} -#grid.grid-2 div.vert { - border-color: red; -} -#grid.grid-2 { - /* Adjustments */ - padding: 0 160px; - width: 660px; +#grid div.vert.first-line{ + + margin-left: 19px; + } + /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ #grid div.horiz{ /* 20px line height */ height: 19px; border-bottom: 1px dotted darkgray; margin: 0; padding: 0; +} + +/** +* Classes for multiple grids +* +* When using more than one grid, remember to set the numberOfGrids +* option in the hashgrid.js file. +*/ +#grid.grid-1 div.vert{ + + /* Vertical grid line colour for grid 1 */ + border-color: darkturquoise; + +} +#grid.grid-2{ + + /* Adjustments */ + padding: 0 160px; + width: 660px; + +} +#grid.grid-2 div.vert{ + + /* Vertical grid line colour for grid 2 */ + border-color: crimson; + } </textarea></li> <li><h3>Modify #grid to suit your needs</h3> <p>The CSS and JavaScript is annotated to help you.</p></li> </ol> <h2 id="usage">Usage</h2> <p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p> <dl> <dt><span class="key">G</span></dt> <dd>Show the grid until you release.</dd> <dt><span class="key">G</span> + <span class="key">H</span></dt> <dd>Show and hold the grid (<span class="key">G</span> will remove it again).</dd> <dt><span class="key">G</span> + <span class="key">F</span></dt> <dd>Toggle the grid to the foreground and back. Pressing <span class="key">F</span> while the grid is held also works.</dd> <dt><span class="key">G</span> + <span class="key">J</span></dt> <dd>Jump to the next grid. Pressing <span class="key">J</span> while the grid is held also works.</dd> </dl> <p><em>N.B. A cookie conveniently remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em></p> <h2 id="release-notes">Release Notes</h2> <dl> +<dt>v5&#8201;&#8212;&#8201;3 Nov 2010</dt> +<dd> +<ul> +<li>Vertical grid lines can now be set using CSS&#8212; images are no longer required! Thanks to <a href="http://twitter.com/coates">Sean Coates</a> for the contribution.</li> +<li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li> +<li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who&#8217;s given feedback.</li> +</ul> +</dd> <dt>v4&#8201;&#8212;&#8201;29 Mar 2010</dt> <dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd> <dt>v3&#8201;&#8212;&#8201;22 Feb 2010</dt> <dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd> <dt>v2&#8201;&#8212;&#8201;2 Feb 2010</dt> <dd>Keys are now more easily configured (see top of hashgrid.js). Renamed the GridOverlay object to hashgrid. Fixed crash when using with disabled CSS.</dd> <dt>v1&#8201;&#8212;&#8201;21 Dec 2009</dt> <dd>First release.</dd> </dl> <h2 id="known-issues">Known Issues</h2> <ul> <li><del>IE 8: Fully functional, but the default <span class="key">ALT</span> + <span class="key">G</span> + <span class="key">ENTER</span> shortcut puts IE into full screen mode. Hit <span class="key">ALT</span> + <span class="key">ENTER</span> to toggle full screen mode off again.</del><ins datetime="2010-02-22"> The default keyboard shortcuts have been changed.</ins></li> <li>IE 6: The grid is always in the foreground.</li> <li>Opera 9/10: Using <span class="key">CTRL</span> or <span class="key">ALT</span> as a modifier key will not work due to different key handling by the browser.</li> </ul> <h2 id="license">License</h2> <p>Released under a <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike License</a>, which essentially means that you&#8217;re free to copy it and adapt it. <a href="http://analog.coop/#talk-to-us">Contact us at Analog</a> if you need a different license.</p> <div id="footer" role="contentinfo"> <p>#grid is an <a href="http://analog.coop/">Analog</a> gig. It was conceived by <a href="http://jontangerine.com/">Jon Tan</a>, and built by <a href="http://accessibility.co.uk/">Jon Gibbins</a>, in cahoots with our <a href="http://analog.coop#is">fine friends</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p> </div> </div> <!-- Grab latest version of jQuery --> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <!-- Include the hashgrid script --> <script type="text/javascript" src="hashgrid.js"></script> </body> </html>
dotjay/hashgrid
b68edfc6c7e3dbb6ea7d4712449541ace03db53e
Document version 5
diff --git a/hashgrid.js b/hashgrid.js index 65ffbb2..db7af79 100644 --- a/hashgrid.js +++ b/hashgrid.js @@ -1,337 +1,340 @@ /** * hashgrid (jQuery version) * http://github.com/dotjay/hashgrid - * Version 4, 29 Mar 2010 - * By Jon Gibbins, accessibility.co.uk + * Version 5, 3 Nov 2010 + * Written by Jon Gibbins, dotjay.co.uk, accessibility.co.uk + * Contibutors: + * Sean Coates, seancoates.com + * Phil Dokas, jetless.org * * // Using a basic #grid setup * var grid = new hashgrid(); * * // Using #grid with a custom id (e.g. #mygrid) * var grid = new hashgrid("mygrid"); * * // Using #grid with additional options * var grid = new hashgrid({ * id: 'mygrid', // id for the grid container * modifierKey: 'alt', // optional 'ctrl', 'alt' or 'shift' * showGridKey: 's', // key to show the grid * holdGridKey: 'enter', // key to hold the grid in place * foregroundKey: 'f', // key to toggle foreground/background * jumpGridsKey: 'd', // key to cycle through the grid classes * numberOfGrids: 2, // number of grid classes used * classPrefix: 'class', // prefix for the grid classes * cookiePrefix: 'mygrid' // prefix for the cookie name * }); */ if (typeof jQuery == "undefined") { alert("Hashgrid: jQuery not loaded. Make sure it's linked to your pages."); } /** * hashgrid overlay */ var hashgrid = function(set) { var options = { id: 'grid', // id for the grid container modifierKey: null, // optional 'ctrl', 'alt' or 'shift' showGridKey: 'g', // key to show the grid holdGridKey: 'h', // key to hold the grid in place foregroundKey: 'f', // key to toggle foreground/background jumpGridsKey: 'j', // key to cycle through the grid classes numberOfGrids: 1, // number of grid classes used classPrefix: 'grid-', // prefix for the grid classes cookiePrefix: 'hashgrid'// prefix for the cookie name }; var overlayOn = false, sticky = false, overlayZState = 'B', overlayZBackground = -1, overlayZForeground = 9999, classNumber = 1; // Apply options if (typeof set == 'object') { var k; for (k in set) options[k] = set[k]; } else if (typeof set == 'string') { options.id = set; } // Remove any conflicting overlay if ($('#' + options.id).length > 0) { $('#' + options.id).remove(); } // Create overlay, hidden before adding to DOM var overlayEl = $('<div></div>'); overlayEl .attr('id', options.id) .css({ display: 'none', 'pointer-events': 'none' }); $("body").prepend(overlayEl); var overlay = $('#' + options.id); // Unless a custom z-index is set, ensure the overlay will be behind everything if (overlay.css('z-index') == 'auto') overlay.css('z-index', overlayZBackground); // Override the default overlay height with the actual page height var pageHeight = parseFloat($(document).height()); overlay.height(pageHeight); // Add the first grid line so that we can measure it overlay.append('<div id="' + options.id + '-horiz" class="horiz first-line">'); // Position off-screen and display to calculate height var top = overlay.css("top"); overlay.css({ top: "-999px", display: "block" }); // Calculate the number of grid lines needed var line = $('#' + options.id + '-horiz'), lineHeight = line.outerHeight(); // Hide and reset top overlay.css({ display: "none", top: top }); // Break on zero line height if (lineHeight <= 0) return true; // Add the remaining grid lines var i, numGridLines = Math.floor(pageHeight / lineHeight); for (i = numGridLines - 1; i >= 1; i--) { overlay.append('<div class="horiz"></div>'); } // vertical grid overlay.append($('<div class="vert-container"></div>')); var overlayVert = overlay.children('.vert-container'); var gridWidth = overlay.width(); overlayVert.css({width: gridWidth, position: 'absolute', top: 0}); overlayVert.append('<div class="vert first-line">&nbsp;</div>'); // 30 is an arbitrarily large number... // can't calculate the margin width properly for (i = 0; i < 30; i++) { overlayVert.append('<div class="vert">&nbsp;</div>'); } overlayVert.children() .height(pageHeight) .css({display: 'inline-block'}); // Check for saved state var overlayCookie = readCookie(options.cookiePrefix + options.id); if (typeof overlayCookie == 'string') { var state = overlayCookie.split(','); state[2] = Number(state[2]); if ((typeof state[2] == 'number') && !isNaN(state[2])) { classNumber = state[2].toFixed(0); overlay.addClass(options.classPrefix + classNumber); } if (state[1] == 'F') { overlayZState = 'F'; overlay.css('z-index', overlayZForeground); } if (state[0] == '1') { overlayOn = true; sticky = true; showOverlay(); } } else { overlay.addClass(options.classPrefix + classNumber); } // Keyboard controls $(document).bind('keydown', keydownHandler); $(document).bind('keyup', keyupHandler); /** * Helpers */ function getModifier(e) { if (options.modifierKey == null) return true; // Bypass by default var m = true; switch(options.modifierKey) { case 'ctrl': m = (e.ctrlKey ? e.ctrlKey : false); break; case 'alt': m = (e.altKey ? e.altKey : false); break; case 'shift': m = (e.shiftKey ? e.shiftKey : false); break; } return m; } function getKey(e) { var k = false, c = (e.keyCode ? e.keyCode : e.which); // Handle keywords if (c == 13) k = 'enter'; // Handle letters else k = String.fromCharCode(c).toLowerCase(); return k; } function saveState() { createCookie(options.cookiePrefix + options.id, (sticky ? '1' : '0') + ',' + overlayZState + ',' + classNumber, 1); } function showOverlay() { overlay.show(); overlayVert.css({width: overlay.width()}); // hide any vertical blocks that aren't at the top of the viewport overlayVert.children('.vert').each(function () { $(this).css('display','inline-block'); if ($(this).offset().top > 0) { $(this).hide(); } }); } /** * Event handlers */ function keydownHandler(e) { var source = e.target.tagName.toLowerCase(); if ((source == 'input') || (source == 'textarea') || (source == 'select')) return true; var m = getModifier(e); if (!m) return true; var k = getKey(e); if (!k) return true; switch(k) { case options.showGridKey: if (!overlayOn) { showOverlay(); overlayOn = true; } else if (sticky) { overlay.hide(); overlayOn = false; sticky = false; saveState(); } break; case options.holdGridKey: if (overlayOn && !sticky) { // Turn sticky overlay on sticky = true; saveState(); } break; case options.foregroundKey: if (overlayOn) { // Toggle sticky overlay z-index if (overlay.css('z-index') == overlayZForeground) { overlay.css('z-index', overlayZBackground); overlayZState = 'B'; } else { overlay.css('z-index', overlayZForeground); overlayZState = 'F'; } saveState(); } break; case options.jumpGridsKey: if (overlayOn && (options.numberOfGrids > 1)) { // Cycle through the available grids overlay.removeClass(options.classPrefix + classNumber); classNumber++; if (classNumber > options.numberOfGrids) classNumber = 1; overlay.addClass(options.classPrefix + classNumber); showOverlay(); if (/webkit/.test( navigator.userAgent.toLowerCase() )) { forceRepaint(); } saveState(); } break; } } function keyupHandler(e) { var m = getModifier(e); if (!m) return true; var k = getKey(e); if (!k) return true; if ((k == options.showGridKey) && !sticky) { overlay.hide(); overlayOn = false; } } /** * Cookie functions * * By Peter-Paul Koch: * http://www.quirksmode.org/js/cookies.html */ function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function eraseCookie(name) { createCookie(name,"",-1); } /** * Forces a repaint (because WebKit has issues) * http://www.sitepoint.com/forums/showthread.php?p=4538763 * http://www.phpied.com/the-new-game-show-will-it-reflow/ */ function forceRepaint() { var ss = document.styleSheets[0]; try { ss.addRule('.xxxxxx', 'position: relative'); ss.removeRule(ss.rules.length - 1); } catch(e){} } } /** * You can call hashgrid from your own code, but it's loaded here as * an example for your convenience. */ $(document).ready(function() { var grid = new hashgrid({ numberOfGrids: 2 }); });
dotjay/hashgrid
bb6c1294f0fa70df3c1d64ae908369942bffeab6
Move supporting functions inside the hashgrid declaration so as to not muddy global scope.
diff --git a/hashgrid.js b/hashgrid.js index b9ef61c..65ffbb2 100644 --- a/hashgrid.js +++ b/hashgrid.js @@ -1,339 +1,337 @@ /** * hashgrid (jQuery version) * http://github.com/dotjay/hashgrid * Version 4, 29 Mar 2010 * By Jon Gibbins, accessibility.co.uk * * // Using a basic #grid setup * var grid = new hashgrid(); * * // Using #grid with a custom id (e.g. #mygrid) * var grid = new hashgrid("mygrid"); * * // Using #grid with additional options * var grid = new hashgrid({ * id: 'mygrid', // id for the grid container * modifierKey: 'alt', // optional 'ctrl', 'alt' or 'shift' * showGridKey: 's', // key to show the grid * holdGridKey: 'enter', // key to hold the grid in place * foregroundKey: 'f', // key to toggle foreground/background * jumpGridsKey: 'd', // key to cycle through the grid classes * numberOfGrids: 2, // number of grid classes used * classPrefix: 'class', // prefix for the grid classes * cookiePrefix: 'mygrid' // prefix for the cookie name * }); */ if (typeof jQuery == "undefined") { alert("Hashgrid: jQuery not loaded. Make sure it's linked to your pages."); } /** * hashgrid overlay */ var hashgrid = function(set) { var options = { id: 'grid', // id for the grid container modifierKey: null, // optional 'ctrl', 'alt' or 'shift' showGridKey: 'g', // key to show the grid holdGridKey: 'h', // key to hold the grid in place foregroundKey: 'f', // key to toggle foreground/background jumpGridsKey: 'j', // key to cycle through the grid classes numberOfGrids: 1, // number of grid classes used classPrefix: 'grid-', // prefix for the grid classes cookiePrefix: 'hashgrid'// prefix for the cookie name }; var overlayOn = false, sticky = false, overlayZState = 'B', overlayZBackground = -1, overlayZForeground = 9999, classNumber = 1; // Apply options if (typeof set == 'object') { var k; for (k in set) options[k] = set[k]; } else if (typeof set == 'string') { options.id = set; } // Remove any conflicting overlay if ($('#' + options.id).length > 0) { $('#' + options.id).remove(); } // Create overlay, hidden before adding to DOM var overlayEl = $('<div></div>'); overlayEl .attr('id', options.id) .css({ display: 'none', 'pointer-events': 'none' }); $("body").prepend(overlayEl); var overlay = $('#' + options.id); // Unless a custom z-index is set, ensure the overlay will be behind everything if (overlay.css('z-index') == 'auto') overlay.css('z-index', overlayZBackground); // Override the default overlay height with the actual page height var pageHeight = parseFloat($(document).height()); overlay.height(pageHeight); // Add the first grid line so that we can measure it overlay.append('<div id="' + options.id + '-horiz" class="horiz first-line">'); // Position off-screen and display to calculate height var top = overlay.css("top"); overlay.css({ top: "-999px", display: "block" }); // Calculate the number of grid lines needed var line = $('#' + options.id + '-horiz'), lineHeight = line.outerHeight(); // Hide and reset top overlay.css({ display: "none", top: top }); // Break on zero line height if (lineHeight <= 0) return true; // Add the remaining grid lines var i, numGridLines = Math.floor(pageHeight / lineHeight); for (i = numGridLines - 1; i >= 1; i--) { overlay.append('<div class="horiz"></div>'); } // vertical grid overlay.append($('<div class="vert-container"></div>')); var overlayVert = overlay.children('.vert-container'); var gridWidth = overlay.width(); overlayVert.css({width: gridWidth, position: 'absolute', top: 0}); overlayVert.append('<div class="vert first-line">&nbsp;</div>'); // 30 is an arbitrarily large number... // can't calculate the margin width properly for (i = 0; i < 30; i++) { overlayVert.append('<div class="vert">&nbsp;</div>'); } overlayVert.children() .height(pageHeight) .css({display: 'inline-block'}); // Check for saved state var overlayCookie = readCookie(options.cookiePrefix + options.id); if (typeof overlayCookie == 'string') { var state = overlayCookie.split(','); state[2] = Number(state[2]); if ((typeof state[2] == 'number') && !isNaN(state[2])) { classNumber = state[2].toFixed(0); overlay.addClass(options.classPrefix + classNumber); } if (state[1] == 'F') { overlayZState = 'F'; overlay.css('z-index', overlayZForeground); } if (state[0] == '1') { overlayOn = true; sticky = true; showOverlay(); } } else { overlay.addClass(options.classPrefix + classNumber); } // Keyboard controls $(document).bind('keydown', keydownHandler); $(document).bind('keyup', keyupHandler); /** * Helpers */ function getModifier(e) { if (options.modifierKey == null) return true; // Bypass by default var m = true; switch(options.modifierKey) { case 'ctrl': m = (e.ctrlKey ? e.ctrlKey : false); break; case 'alt': m = (e.altKey ? e.altKey : false); break; case 'shift': m = (e.shiftKey ? e.shiftKey : false); break; } return m; } function getKey(e) { var k = false, c = (e.keyCode ? e.keyCode : e.which); // Handle keywords if (c == 13) k = 'enter'; // Handle letters else k = String.fromCharCode(c).toLowerCase(); return k; } function saveState() { createCookie(options.cookiePrefix + options.id, (sticky ? '1' : '0') + ',' + overlayZState + ',' + classNumber, 1); } function showOverlay() { overlay.show(); overlayVert.css({width: overlay.width()}); // hide any vertical blocks that aren't at the top of the viewport overlayVert.children('.vert').each(function () { $(this).css('display','inline-block'); if ($(this).offset().top > 0) { $(this).hide(); } }); } /** * Event handlers */ function keydownHandler(e) { var source = e.target.tagName.toLowerCase(); if ((source == 'input') || (source == 'textarea') || (source == 'select')) return true; var m = getModifier(e); if (!m) return true; var k = getKey(e); if (!k) return true; switch(k) { case options.showGridKey: if (!overlayOn) { showOverlay(); overlayOn = true; } else if (sticky) { overlay.hide(); overlayOn = false; sticky = false; saveState(); } break; case options.holdGridKey: if (overlayOn && !sticky) { // Turn sticky overlay on sticky = true; saveState(); } break; case options.foregroundKey: if (overlayOn) { // Toggle sticky overlay z-index if (overlay.css('z-index') == overlayZForeground) { overlay.css('z-index', overlayZBackground); overlayZState = 'B'; } else { overlay.css('z-index', overlayZForeground); overlayZState = 'F'; } saveState(); } break; case options.jumpGridsKey: if (overlayOn && (options.numberOfGrids > 1)) { // Cycle through the available grids overlay.removeClass(options.classPrefix + classNumber); classNumber++; if (classNumber > options.numberOfGrids) classNumber = 1; overlay.addClass(options.classPrefix + classNumber); showOverlay(); if (/webkit/.test( navigator.userAgent.toLowerCase() )) { forceRepaint(); } saveState(); } break; } } function keyupHandler(e) { var m = getModifier(e); if (!m) return true; var k = getKey(e); if (!k) return true; if ((k == options.showGridKey) && !sticky) { overlay.hide(); overlayOn = false; } } + /** + * Cookie functions + * + * By Peter-Paul Koch: + * http://www.quirksmode.org/js/cookies.html + */ + function createCookie(name,value,days) { + if (days) { + var date = new Date(); + date.setTime(date.getTime()+(days*24*60*60*1000)); + var expires = "; expires="+date.toGMTString(); + } + else var expires = ""; + document.cookie = name+"="+value+expires+"; path=/"; + } + + function readCookie(name) { + var nameEQ = name + "="; + var ca = document.cookie.split(';'); + for(var i=0;i < ca.length;i++) { + var c = ca[i]; + while (c.charAt(0)==' ') c = c.substring(1,c.length); + if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); + } + return null; + } + + function eraseCookie(name) { + createCookie(name,"",-1); + } + + /** + * Forces a repaint (because WebKit has issues) + * http://www.sitepoint.com/forums/showthread.php?p=4538763 + * http://www.phpied.com/the-new-game-show-will-it-reflow/ + */ + function forceRepaint() { + var ss = document.styleSheets[0]; + try { + ss.addRule('.xxxxxx', 'position: relative'); + ss.removeRule(ss.rules.length - 1); + } catch(e){} + } + } /** - * You can call hashgrid from your own code, but it's loaded here by - * default for convenience. + * You can call hashgrid from your own code, but it's loaded here as + * an example for your convenience. */ $(document).ready(function() { var grid = new hashgrid({ numberOfGrids: 2 }); }); - - -/** - * Cookie functions - * - * By Peter-Paul Koch: - * http://www.quirksmode.org/js/cookies.html - */ -function createCookie(name,value,days) { - if (days) { - var date = new Date(); - date.setTime(date.getTime()+(days*24*60*60*1000)); - var expires = "; expires="+date.toGMTString(); - } - else var expires = ""; - document.cookie = name+"="+value+expires+"; path=/"; -} - -function readCookie(name) { - var nameEQ = name + "="; - var ca = document.cookie.split(';'); - for(var i=0;i < ca.length;i++) { - var c = ca[i]; - while (c.charAt(0)==' ') c = c.substring(1,c.length); - if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); - } - return null; -} - -function eraseCookie(name) { - createCookie(name,"",-1); -} - - -/** - * Forces a repaint (because WebKit has issues) - * http://www.sitepoint.com/forums/showthread.php?p=4538763 - * http://www.phpied.com/the-new-game-show-will-it-reflow/ - */ -function forceRepaint() { - var ss = document.styleSheets[0]; - try { - ss.addRule('.xxxxxx', 'position: relative'); - ss.removeRule(ss.rules.length - 1); - } catch(e){} -}
dotjay/hashgrid
2201e58ed6d9506de68138e9159058e997622012
Move init call below declaration of hashgrid.
diff --git a/hashgrid.js b/hashgrid.js index ad54b2f..b9ef61c 100644 --- a/hashgrid.js +++ b/hashgrid.js @@ -1,339 +1,339 @@ /** * hashgrid (jQuery version) * http://github.com/dotjay/hashgrid * Version 4, 29 Mar 2010 * By Jon Gibbins, accessibility.co.uk * * // Using a basic #grid setup * var grid = new hashgrid(); * * // Using #grid with a custom id (e.g. #mygrid) * var grid = new hashgrid("mygrid"); * * // Using #grid with additional options * var grid = new hashgrid({ * id: 'mygrid', // id for the grid container * modifierKey: 'alt', // optional 'ctrl', 'alt' or 'shift' * showGridKey: 's', // key to show the grid * holdGridKey: 'enter', // key to hold the grid in place * foregroundKey: 'f', // key to toggle foreground/background * jumpGridsKey: 'd', // key to cycle through the grid classes * numberOfGrids: 2, // number of grid classes used * classPrefix: 'class', // prefix for the grid classes * cookiePrefix: 'mygrid' // prefix for the cookie name * }); */ if (typeof jQuery == "undefined") { alert("Hashgrid: jQuery not loaded. Make sure it's linked to your pages."); } -/** - * You can call hashgrid from your own code, but it's loaded here by - * default for convenience. - */ -$(document).ready(function() { - - var grid = new hashgrid({ - numberOfGrids: 2 - }); - -}); - - /** * hashgrid overlay */ var hashgrid = function(set) { var options = { id: 'grid', // id for the grid container modifierKey: null, // optional 'ctrl', 'alt' or 'shift' showGridKey: 'g', // key to show the grid holdGridKey: 'h', // key to hold the grid in place foregroundKey: 'f', // key to toggle foreground/background jumpGridsKey: 'j', // key to cycle through the grid classes numberOfGrids: 1, // number of grid classes used classPrefix: 'grid-', // prefix for the grid classes cookiePrefix: 'hashgrid'// prefix for the cookie name }; var overlayOn = false, sticky = false, overlayZState = 'B', overlayZBackground = -1, overlayZForeground = 9999, classNumber = 1; // Apply options if (typeof set == 'object') { var k; for (k in set) options[k] = set[k]; } else if (typeof set == 'string') { options.id = set; } // Remove any conflicting overlay if ($('#' + options.id).length > 0) { $('#' + options.id).remove(); } // Create overlay, hidden before adding to DOM var overlayEl = $('<div></div>'); overlayEl .attr('id', options.id) .css({ display: 'none', 'pointer-events': 'none' }); $("body").prepend(overlayEl); var overlay = $('#' + options.id); // Unless a custom z-index is set, ensure the overlay will be behind everything if (overlay.css('z-index') == 'auto') overlay.css('z-index', overlayZBackground); // Override the default overlay height with the actual page height var pageHeight = parseFloat($(document).height()); overlay.height(pageHeight); // Add the first grid line so that we can measure it overlay.append('<div id="' + options.id + '-horiz" class="horiz first-line">'); // Position off-screen and display to calculate height var top = overlay.css("top"); overlay.css({ top: "-999px", display: "block" }); // Calculate the number of grid lines needed var line = $('#' + options.id + '-horiz'), lineHeight = line.outerHeight(); // Hide and reset top overlay.css({ display: "none", top: top }); // Break on zero line height if (lineHeight <= 0) return true; // Add the remaining grid lines var i, numGridLines = Math.floor(pageHeight / lineHeight); for (i = numGridLines - 1; i >= 1; i--) { overlay.append('<div class="horiz"></div>'); } // vertical grid overlay.append($('<div class="vert-container"></div>')); var overlayVert = overlay.children('.vert-container'); var gridWidth = overlay.width(); overlayVert.css({width: gridWidth, position: 'absolute', top: 0}); overlayVert.append('<div class="vert first-line">&nbsp;</div>'); // 30 is an arbitrarily large number... // can't calculate the margin width properly for (i = 0; i < 30; i++) { overlayVert.append('<div class="vert">&nbsp;</div>'); } overlayVert.children() .height(pageHeight) .css({display: 'inline-block'}); // Check for saved state var overlayCookie = readCookie(options.cookiePrefix + options.id); if (typeof overlayCookie == 'string') { var state = overlayCookie.split(','); state[2] = Number(state[2]); if ((typeof state[2] == 'number') && !isNaN(state[2])) { classNumber = state[2].toFixed(0); overlay.addClass(options.classPrefix + classNumber); } if (state[1] == 'F') { overlayZState = 'F'; overlay.css('z-index', overlayZForeground); } if (state[0] == '1') { overlayOn = true; sticky = true; showOverlay(); } } else { overlay.addClass(options.classPrefix + classNumber); } // Keyboard controls $(document).bind('keydown', keydownHandler); $(document).bind('keyup', keyupHandler); /** * Helpers */ function getModifier(e) { if (options.modifierKey == null) return true; // Bypass by default var m = true; switch(options.modifierKey) { case 'ctrl': m = (e.ctrlKey ? e.ctrlKey : false); break; case 'alt': m = (e.altKey ? e.altKey : false); break; case 'shift': m = (e.shiftKey ? e.shiftKey : false); break; } return m; } function getKey(e) { var k = false, c = (e.keyCode ? e.keyCode : e.which); // Handle keywords if (c == 13) k = 'enter'; // Handle letters else k = String.fromCharCode(c).toLowerCase(); return k; } function saveState() { createCookie(options.cookiePrefix + options.id, (sticky ? '1' : '0') + ',' + overlayZState + ',' + classNumber, 1); } function showOverlay() { overlay.show(); overlayVert.css({width: overlay.width()}); // hide any vertical blocks that aren't at the top of the viewport overlayVert.children('.vert').each(function () { $(this).css('display','inline-block'); if ($(this).offset().top > 0) { $(this).hide(); } }); } /** * Event handlers */ function keydownHandler(e) { var source = e.target.tagName.toLowerCase(); if ((source == 'input') || (source == 'textarea') || (source == 'select')) return true; var m = getModifier(e); if (!m) return true; var k = getKey(e); if (!k) return true; switch(k) { case options.showGridKey: if (!overlayOn) { showOverlay(); overlayOn = true; } else if (sticky) { overlay.hide(); overlayOn = false; sticky = false; saveState(); } break; case options.holdGridKey: if (overlayOn && !sticky) { // Turn sticky overlay on sticky = true; saveState(); } break; case options.foregroundKey: if (overlayOn) { // Toggle sticky overlay z-index if (overlay.css('z-index') == overlayZForeground) { overlay.css('z-index', overlayZBackground); overlayZState = 'B'; } else { overlay.css('z-index', overlayZForeground); overlayZState = 'F'; } saveState(); } break; case options.jumpGridsKey: if (overlayOn && (options.numberOfGrids > 1)) { // Cycle through the available grids overlay.removeClass(options.classPrefix + classNumber); classNumber++; if (classNumber > options.numberOfGrids) classNumber = 1; overlay.addClass(options.classPrefix + classNumber); showOverlay(); if (/webkit/.test( navigator.userAgent.toLowerCase() )) { forceRepaint(); } saveState(); } break; } } function keyupHandler(e) { var m = getModifier(e); if (!m) return true; var k = getKey(e); if (!k) return true; if ((k == options.showGridKey) && !sticky) { overlay.hide(); overlayOn = false; } } } +/** + * You can call hashgrid from your own code, but it's loaded here by + * default for convenience. + */ +$(document).ready(function() { + + var grid = new hashgrid({ + numberOfGrids: 2 + }); + +}); + + /** * Cookie functions * * By Peter-Paul Koch: * http://www.quirksmode.org/js/cookies.html */ function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function eraseCookie(name) { createCookie(name,"",-1); } /** * Forces a repaint (because WebKit has issues) * http://www.sitepoint.com/forums/showthread.php?p=4538763 * http://www.phpied.com/the-new-game-show-will-it-reflow/ */ function forceRepaint() { var ss = document.styleSheets[0]; try { ss.addRule('.xxxxxx', 'position: relative'); ss.removeRule(ss.rules.length - 1); } catch(e){} }
dotjay/hashgrid
f1edc7597c6af544ac93a8094483517902339383
Adding a little check for presence of jQuery.
diff --git a/hashgrid.js b/hashgrid.js index ae26897..ad54b2f 100644 --- a/hashgrid.js +++ b/hashgrid.js @@ -1,336 +1,339 @@ /** * hashgrid (jQuery version) * http://github.com/dotjay/hashgrid * Version 4, 29 Mar 2010 * By Jon Gibbins, accessibility.co.uk * * // Using a basic #grid setup * var grid = new hashgrid(); * * // Using #grid with a custom id (e.g. #mygrid) * var grid = new hashgrid("mygrid"); * * // Using #grid with additional options * var grid = new hashgrid({ * id: 'mygrid', // id for the grid container * modifierKey: 'alt', // optional 'ctrl', 'alt' or 'shift' * showGridKey: 's', // key to show the grid * holdGridKey: 'enter', // key to hold the grid in place * foregroundKey: 'f', // key to toggle foreground/background * jumpGridsKey: 'd', // key to cycle through the grid classes * numberOfGrids: 2, // number of grid classes used * classPrefix: 'class', // prefix for the grid classes * cookiePrefix: 'mygrid' // prefix for the cookie name * }); */ +if (typeof jQuery == "undefined") { + alert("Hashgrid: jQuery not loaded. Make sure it's linked to your pages."); +} /** * You can call hashgrid from your own code, but it's loaded here by * default for convenience. */ $(document).ready(function() { var grid = new hashgrid({ numberOfGrids: 2 }); }); /** * hashgrid overlay */ var hashgrid = function(set) { var options = { id: 'grid', // id for the grid container modifierKey: null, // optional 'ctrl', 'alt' or 'shift' showGridKey: 'g', // key to show the grid holdGridKey: 'h', // key to hold the grid in place foregroundKey: 'f', // key to toggle foreground/background jumpGridsKey: 'j', // key to cycle through the grid classes numberOfGrids: 1, // number of grid classes used classPrefix: 'grid-', // prefix for the grid classes cookiePrefix: 'hashgrid'// prefix for the cookie name }; var overlayOn = false, sticky = false, overlayZState = 'B', overlayZBackground = -1, overlayZForeground = 9999, classNumber = 1; // Apply options if (typeof set == 'object') { var k; for (k in set) options[k] = set[k]; } else if (typeof set == 'string') { options.id = set; } // Remove any conflicting overlay if ($('#' + options.id).length > 0) { $('#' + options.id).remove(); } // Create overlay, hidden before adding to DOM var overlayEl = $('<div></div>'); overlayEl .attr('id', options.id) .css({ display: 'none', 'pointer-events': 'none' }); $("body").prepend(overlayEl); var overlay = $('#' + options.id); // Unless a custom z-index is set, ensure the overlay will be behind everything if (overlay.css('z-index') == 'auto') overlay.css('z-index', overlayZBackground); // Override the default overlay height with the actual page height var pageHeight = parseFloat($(document).height()); overlay.height(pageHeight); // Add the first grid line so that we can measure it overlay.append('<div id="' + options.id + '-horiz" class="horiz first-line">'); // Position off-screen and display to calculate height var top = overlay.css("top"); overlay.css({ top: "-999px", display: "block" }); // Calculate the number of grid lines needed var line = $('#' + options.id + '-horiz'), lineHeight = line.outerHeight(); // Hide and reset top overlay.css({ display: "none", top: top }); // Break on zero line height if (lineHeight <= 0) return true; // Add the remaining grid lines var i, numGridLines = Math.floor(pageHeight / lineHeight); for (i = numGridLines - 1; i >= 1; i--) { overlay.append('<div class="horiz"></div>'); } // vertical grid overlay.append($('<div class="vert-container"></div>')); var overlayVert = overlay.children('.vert-container'); var gridWidth = overlay.width(); overlayVert.css({width: gridWidth, position: 'absolute', top: 0}); overlayVert.append('<div class="vert first-line">&nbsp;</div>'); // 30 is an arbitrarily large number... // can't calculate the margin width properly for (i = 0; i < 30; i++) { overlayVert.append('<div class="vert">&nbsp;</div>'); } overlayVert.children() .height(pageHeight) .css({display: 'inline-block'}); // Check for saved state var overlayCookie = readCookie(options.cookiePrefix + options.id); if (typeof overlayCookie == 'string') { var state = overlayCookie.split(','); state[2] = Number(state[2]); if ((typeof state[2] == 'number') && !isNaN(state[2])) { classNumber = state[2].toFixed(0); overlay.addClass(options.classPrefix + classNumber); } if (state[1] == 'F') { overlayZState = 'F'; overlay.css('z-index', overlayZForeground); } if (state[0] == '1') { overlayOn = true; sticky = true; showOverlay(); } } else { overlay.addClass(options.classPrefix + classNumber); } // Keyboard controls $(document).bind('keydown', keydownHandler); $(document).bind('keyup', keyupHandler); /** * Helpers */ function getModifier(e) { if (options.modifierKey == null) return true; // Bypass by default var m = true; switch(options.modifierKey) { case 'ctrl': m = (e.ctrlKey ? e.ctrlKey : false); break; case 'alt': m = (e.altKey ? e.altKey : false); break; case 'shift': m = (e.shiftKey ? e.shiftKey : false); break; } return m; } function getKey(e) { var k = false, c = (e.keyCode ? e.keyCode : e.which); // Handle keywords if (c == 13) k = 'enter'; // Handle letters else k = String.fromCharCode(c).toLowerCase(); return k; } function saveState() { createCookie(options.cookiePrefix + options.id, (sticky ? '1' : '0') + ',' + overlayZState + ',' + classNumber, 1); } function showOverlay() { overlay.show(); overlayVert.css({width: overlay.width()}); // hide any vertical blocks that aren't at the top of the viewport overlayVert.children('.vert').each(function () { $(this).css('display','inline-block'); if ($(this).offset().top > 0) { $(this).hide(); } }); } /** * Event handlers */ function keydownHandler(e) { var source = e.target.tagName.toLowerCase(); if ((source == 'input') || (source == 'textarea') || (source == 'select')) return true; var m = getModifier(e); if (!m) return true; var k = getKey(e); if (!k) return true; switch(k) { case options.showGridKey: if (!overlayOn) { showOverlay(); overlayOn = true; } else if (sticky) { overlay.hide(); overlayOn = false; sticky = false; saveState(); } break; case options.holdGridKey: if (overlayOn && !sticky) { // Turn sticky overlay on sticky = true; saveState(); } break; case options.foregroundKey: if (overlayOn) { // Toggle sticky overlay z-index if (overlay.css('z-index') == overlayZForeground) { overlay.css('z-index', overlayZBackground); overlayZState = 'B'; } else { overlay.css('z-index', overlayZForeground); overlayZState = 'F'; } saveState(); } break; case options.jumpGridsKey: if (overlayOn && (options.numberOfGrids > 1)) { // Cycle through the available grids overlay.removeClass(options.classPrefix + classNumber); classNumber++; if (classNumber > options.numberOfGrids) classNumber = 1; overlay.addClass(options.classPrefix + classNumber); showOverlay(); if (/webkit/.test( navigator.userAgent.toLowerCase() )) { forceRepaint(); } saveState(); } break; } } function keyupHandler(e) { var m = getModifier(e); if (!m) return true; var k = getKey(e); if (!k) return true; if ((k == options.showGridKey) && !sticky) { overlay.hide(); overlayOn = false; } } } /** * Cookie functions * * By Peter-Paul Koch: * http://www.quirksmode.org/js/cookies.html */ function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function eraseCookie(name) { createCookie(name,"",-1); } /** * Forces a repaint (because WebKit has issues) * http://www.sitepoint.com/forums/showthread.php?p=4538763 * http://www.phpied.com/the-new-game-show-will-it-reflow/ */ function forceRepaint() { var ss = document.styleSheets[0]; try { ss.addRule('.xxxxxx', 'position: relative'); ss.removeRule(ss.rules.length - 1); } catch(e){} }
dotjay/hashgrid
93ba010951e3aea86eca1148bc7d56bf4ffef520
Link to tagged version of hashgrid instead of the master, which may still be in development and not to be used.
diff --git a/index.htm b/index.htm index 546f60e..33fa91f 100644 --- a/index.htm +++ b/index.htm @@ -1,375 +1,375 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>#grid</title> <style type="text/css"> /* Putting inline rules here so the document can be downloaded with style */ body{ font-size: 1em; line-height: 1.25; font-family: Arial, sans-serif; background: White; color: DimGray; margin: 0; padding: 0 20px; } #content{ font-size: 16px; line-height: 20px; position: relative; } #content{ width: 620px; margin: 0 auto; } #footer{ border-top: 1px dotted DarkGray; padding-top: 19px; } h1, h2{ color: Black; font-weight: normal; } h1{ font-size: 36px; line-height: 40px; margin: 40px 0 20px; padding-bottom: 19px; border-bottom: 1px dotted DarkGray; } h1 em{ font-style: normal; color: DarkGray; font-size: 16px; line-height: 20px; margin: 0 0 20px; } h2, h3{ font-size: 16px; font-weight: 700; line-height: 20px; margin: 0 0 20px; } h3{ font-weight: 300; } a:link, a:visited{ color: Black; text-decoration: none; padding: 0 2px; background-color: WhiteSmoke; border-bottom: 1px solid Gold; } a:focus{ outline: none; } a:focus, a:hover, a:active{ background-color: Khaki; border-bottom: 1px solid GoldenRod; } p, ul{ padding: 0; margin: 0 0 20px; } dl, ol{ padding: 0; margin: 0; } ul{ list-style: circle; } ol li{ margin-bottom: 20px; } dd{ margin: 0 0 20px 0; } del{ text-decoration: line-through; opacity: 0.75; } ins{ text-decoration: none; } code{ font-size: 14px; line-height: 1; } textarea{ font-family: 'Courier New', monospace; font-size: 14px; line-height: 20px; display: block; width: 600px; margin: 0 0 20px; padding: 0 0 0 15px; border: 0; color: Black; background: Gainsboro; border-left: 5px solid DarkGray; } #javascript-code{ height: 180px; } #css-code{ height: 1300px; } .summary em{ font-style: normal; position: absolute; color: DarkGray; right: 0; top: 18px; width: 140px; } .summary em span{ position: absolute; left: -9999px; } #download{ line-height: 60px; padding: 0 40px 0 15px; border-left: 5px solid DarkGray; background: Gainsboro; color: DimGray; } span.key{ color: Black; text-transform: uppercase; } </style> <!-- Set styles --> <style type="text/css"> /** * Grid */ #grid{ /* Vertical grid lines */ background: url(bg-grid-980.gif) repeat-y 0 0; /* Dimensions - same width as your grid with gutters */ width: 980px; /* Grid (left-aligned) position: absolute; top: 0; left: 0; */ /* Grid (centered) */ position: absolute; top: 0; left: 50%; margin-left: -490px; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option in the hashgrid.js file. */ #grid.grid-1{ /* Vertical grid lines for grid 1 */ background: url(bg-grid-980.gif) repeat-y 0 0; } #grid.grid-2{ /* Vertical grid lines for grid 2 */ background: url(bg-grid-660.gif) repeat-y 160px 0; /* Adjustments */ padding: 0 160px; width: 660px; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ #grid div.horiz{ /* 20px line height */ height: 19px; border-bottom: 1px dotted #aaa; margin: 0; padding: 0; } </style> </head> <body> <div id="content" role="main"> <h1>#grid <em>v4</em></h1> <p class="summary"><em>Mon, 29 Mar 2010<span>:</span></em> This is a little tool we created for our <a href="http://analog.coop/">Analog&#160;holding&#160;page</a>. It inserts a <a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a> in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit <span class="key">G</span> on your keyboard.</p> <h2>Download</h2> <p id="download"><a href="http://github.com/dotjay/hashgrid/downloads">Download #grid</a> from <a href="http://github.com/dotjay/hashgrid">GitHub</a></p> <h2 id="features">Features</h2> <ul> <li>Adaptable for all layout widths and alignments</li> <li>Adaptable for any vertical rhythm value</li> <li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li> <li>Uses a single JavaScript file, a little CSS, and an image (for the vertical lines)</li> </ul> <p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p> <h2 id="installation">Installation</h2> <ol> -<li><h3>Copy the <a href="http://github.com/dotjay/hashgrid/blob/master/hashgrid.js">hashgrid.js</a> script to your project</h3></li> +<li><h3>Copy the <a href="http://github.com/dotjay/hashgrid/blob/v4/hashgrid.js">hashgrid.js</a> script to your project</h3></li> <li><h3>Add the script to your page(s) just inside the <code>&#60;/body&#62;</code> tag</h3> <textarea id="javascript-code" cols="68" rows="8" readonly="readonly"> &#60;!-- Grab latest version of jQuery --&#62; &#60;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"&#62; &#60;/script&#62; &#60;!-- Include the hashgrid script --&#62; &#60;script type="text/javascript" src="hashgrid.js"&#62;&#60;/script&#62;</textarea></li> <li><h3>Add the CSS to your page(s)</h3> <textarea id="css-code" cols="68" rows="64" readonly="readonly"> /** * Grid */ #grid{ /* Vertical grid lines */ background: url(bg-grid-980.gif) repeat-y 0 0; /* Dimensions - same width as your grid with gutters */ width: 980px; /* Grid (left-aligned) position: absolute; top: 0; left: 0; */ /* Grid (centered) */ position: absolute; top: 0; left: 50%; margin-left: -490px; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option in the hashgrid.js file. */ #grid.grid-1{ /* Vertical grid lines for grid 1 */ background: url(bg-grid-980.gif) repeat-y 0 0; } #grid.grid-2{ /* Vertical grid lines for grid 2 */ background: url(bg-grid-660.gif) repeat-y 160px 0; /* Adjustments */ padding: 0 160px; width: 660px; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ #grid div.horiz{ /* 20px line height */ height: 19px; border-bottom: 1px dotted #aaa; margin: 0; padding: 0; } </textarea></li> <li><h3>Modify #grid to suit your needs</h3> <p>The CSS and JavaScript is annotated to help you. We&#8217;ve included a <a href="bg-grid-980.gif">980px-wide background image</a> to provide the vertical grid lines (a 940-pixel-wide content area with 20px gutters). If you&#8217;re working to a <a href="http://www.markboulton.co.uk/journal/comments/five-simple-steps-to-designing-grid-systems-part-1">different grid</a>, you will need to create a new image for your guides. Don&#8217;t forget to make the background transparent!</p></li> </ol> <h2 id="usage">Usage</h2> <p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p> <dl> <dt><span class="key">G</span></dt> <dd>Show the grid until you release.</dd> <dt><span class="key">G</span> + <span class="key">H</span></dt> <dd>Show and hold the grid (<span class="key">G</span> will remove it again).</dd> <dt><span class="key">G</span> + <span class="key">F</span></dt> <dd>Toggle the grid to the foreground and back. Pressing <span class="key">F</span> while the grid is held also works.</dd> <dt><span class="key">G</span> + <span class="key">J</span></dt> <dd>Jump to the next grid. Pressing <span class="key">J</span> while the grid is held also works.</dd> </dl> <p><em>N.B. A cookie conveniently remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em></p> <h2 id="release-notes">Release Notes</h2> <dl> <dt>v4&#8201;&#8212;&#8201;29 Mar 2010</dt> <dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd> <dt>v3&#8201;&#8212;&#8201;22 Feb 2010</dt> <dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd> <dt>v2&#8201;&#8212;&#8201;2 Feb 2010</dt> <dd>Keys are now more easily configured (see top of hashgrid.js). Renamed the GridOverlay object to hashgrid. Fixed crash when using with disabled CSS.</dd> <dt>v1&#8201;&#8212;&#8201;21 Dec 2009</dt> <dd>First release.</dd> </dl> <h2 id="known-issues">Known Issues</h2> <ul> <li><del>IE 8: Fully functional, but the default <span class="key">ALT</span> + <span class="key">G</span> + <span class="key">ENTER</span> shortcut puts IE into full screen mode. Hit <span class="key">ALT</span> + <span class="key">ENTER</span> to toggle full screen mode off again.</del><ins datetime="2010-02-22"> The default keyboard shortcuts have been changed.</ins></li> <li>IE 6: The grid is always in the foreground.</li> <li>Opera 9/10: Using <span class="key">CTRL</span> or <span class="key">ALT</span> as a modifier key will not work due to different key handling by the browser.</li> </ul> <h2 id="license">License</h2> <p>Released under a <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike License</a>, which essentially means that you&#8217;re free to copy it and adapt it. <a href="http://analog.coop/#talk-to-us">Contact us at Analog</a> if you need a different license.</p> <div id="footer" role="contentinfo"> <p>#grid is an <a href="http://analog.coop/">Analog</a> gig. It was conceived by <a href="http://jontangerine.com/">Jon Tan</a>, and built by <a href="http://accessibility.co.uk/">Jon Gibbins</a>, in cahoots with our <a href="http://analog.coop#is">fine friends</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p> </div> </div> <!-- Grab latest version of jQuery --> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <!-- Include the hashgrid script --> <script type="text/javascript" src="hashgrid.js"></script> </body> </html>
dotjay/hashgrid
bfd3f2f37fd48feb7449b696780dbcad162dc4af
Improved grid line height calculation (fixes jQuery 1.4.3 compatibility issue)
diff --git a/hashgrid.js b/hashgrid.js index 7f78c8a..11a3d72 100644 --- a/hashgrid.js +++ b/hashgrid.js @@ -1,290 +1,303 @@ /** * hashgrid (jQuery version) * http://github.com/dotjay/hashgrid * Version 4, 29 Mar 2010 * By Jon Gibbins, accessibility.co.uk * * // Using a basic #grid setup * var grid = new hashgrid(); * * // Using #grid with a custom id (e.g. #mygrid) * var grid = new hashgrid("mygrid"); * * // Using #grid with additional options * var grid = new hashgrid({ * id: 'mygrid', // id for the grid container * modifierKey: 'alt', // optional 'ctrl', 'alt' or 'shift' * showGridKey: 's', // key to show the grid * holdGridKey: 'enter', // key to hold the grid in place * foregroundKey: 'f', // key to toggle foreground/background * jumpGridsKey: 'd', // key to cycle through the grid classes * numberOfGrids: 2, // number of grid classes used * classPrefix: 'class', // prefix for the grid classes * cookiePrefix: 'mygrid' // prefix for the cookie name * }); */ /** * You can call hashgrid from your own code, but it's loaded here by * default for convenience. */ $(document).ready(function() { var grid = new hashgrid({ numberOfGrids: 2 }); }); /** * hashgrid overlay */ var hashgrid = function(set) { var options = { id: 'grid', // id for the grid container modifierKey: null, // optional 'ctrl', 'alt' or 'shift' showGridKey: 'g', // key to show the grid holdGridKey: 'h', // key to hold the grid in place foregroundKey: 'f', // key to toggle foreground/background jumpGridsKey: 'j', // key to cycle through the grid classes numberOfGrids: 1, // number of grid classes used classPrefix: 'grid-', // prefix for the grid classes cookiePrefix: 'hashgrid'// prefix for the cookie name }; var overlayOn = false, sticky = false, overlayZState = 'B', overlayZBackground = -1, overlayZForeground = 9999, classNumber = 1; // Apply options if (typeof set == 'object') { var k; for (k in set) options[k] = set[k]; } else if (typeof set == 'string') { options.id = set; } // Remove any conflicting overlay if ($('#' + options.id).length > 0) { $('#' + options.id).remove(); } // Create overlay, hidden before adding to DOM var overlayEl = $('<div></div>'); overlayEl .attr('id', options.id) .css('display', 'none'); $("body").prepend(overlayEl); var overlay = $('#' + options.id); // Unless a custom z-index is set, ensure the overlay will be behind everything if (overlay.css('z-index') == 'auto') overlay.css('z-index', overlayZBackground); // Override the default overlay height with the actual page height var pageHeight = parseFloat($(document).height()); overlay.height(pageHeight); // Add the first grid line so that we can measure it - overlay.append('<div class="horiz first-line">'); + overlay.append('<div id="' + options.id + '-horiz" class="horiz first-line">'); + + // Position off-screen and display to calculate height + var top = overlay.css("top"); + overlay.css({ + top: "-999px", + display: "block" + }); // Calculate the number of grid lines needed - var overlayGridLines = overlay.children('.horiz'), - overlayGridLineHeight = parseFloat(overlayGridLines.css('height')) + parseFloat(overlayGridLines.css('border-bottom-width')); + var line = $('#' + options.id + '-horiz'), + lineHeight = line.outerHeight(); + + // Hide and reset top + overlay.css({ + display: "none", + top: top + }); // Break on zero line height - if (overlayGridLineHeight <= 0) return true; + if (lineHeight <= 0) return true; // Add the remaining grid lines - var i, numGridLines = Math.floor(pageHeight / overlayGridLineHeight); + var i, numGridLines = Math.floor(pageHeight / lineHeight); for (i = numGridLines - 1; i >= 1; i--) { overlay.append('<div class="horiz"></div>'); } // Check for saved state var overlayCookie = readCookie(options.cookiePrefix + options.id); if (typeof overlayCookie == 'string') { var state = overlayCookie.split(','); state[2] = Number(state[2]); if ((typeof state[2] == 'number') && !isNaN(state[2])) { classNumber = state[2].toFixed(0); overlay.addClass(options.classPrefix + classNumber); } if (state[1] == 'F') { overlayZState = 'F'; overlay.css('z-index', overlayZForeground); } if (state[0] == '1') { overlayOn = true; sticky = true; overlay.show(); } } else { overlay.addClass(options.classPrefix + classNumber) } // Keyboard controls $(document).bind('keydown', keydownHandler); $(document).bind('keyup', keyupHandler); /** * Helpers */ function getModifier(e) { if (options.modifierKey == null) return true; // Bypass by default var m = true; switch(options.modifierKey) { case 'ctrl': m = (e.ctrlKey ? e.ctrlKey : false); break; case 'alt': m = (e.altKey ? e.altKey : false); break; case 'shift': m = (e.shiftKey ? e.shiftKey : false); break; } return m; } function getKey(e) { var k = false, c = (e.keyCode ? e.keyCode : e.which); // Handle keywords if (c == 13) k = 'enter'; // Handle letters else k = String.fromCharCode(c).toLowerCase(); return k; } function saveState() { createCookie(options.cookiePrefix + options.id, (sticky ? '1' : '0') + ',' + overlayZState + ',' + classNumber, 1); } /** * Event handlers */ function keydownHandler(e) { var source = e.target.tagName.toLowerCase(); if ((source == 'input') || (source == 'textarea') || (source == 'select')) return true; var m = getModifier(e); if (!m) return true; var k = getKey(e); if (!k) return true; switch(k) { case options.showGridKey: if (!overlayOn) { overlay.show(); overlayOn = true; } else if (sticky) { overlay.hide(); overlayOn = false; sticky = false; saveState(); } break; case options.holdGridKey: if (overlayOn && !sticky) { // Turn sticky overlay on sticky = true; saveState(); } break; case options.foregroundKey: if (overlayOn) { // Toggle sticky overlay z-index if (overlay.css('z-index') == overlayZForeground) { overlay.css('z-index', overlayZBackground); overlayZState = 'B'; } else { overlay.css('z-index', overlayZForeground); overlayZState = 'F'; } saveState(); } break; case options.jumpGridsKey: if (overlayOn && (options.numberOfGrids > 1)) { // Cycle through the available grids overlay.removeClass(options.classPrefix + classNumber); classNumber++; if (classNumber > options.numberOfGrids) classNumber = 1; overlay.addClass(options.classPrefix + classNumber); if (/webkit/.test( navigator.userAgent.toLowerCase() )) { forceRepaint(); } saveState(); } break; } } function keyupHandler(e) { var m = getModifier(e); if (!m) return true; var k = getKey(e); if (!k) return true; if ((k == options.showGridKey) && !sticky) { overlay.hide(); overlayOn = false; } } } /** * Cookie functions * * By Peter-Paul Koch: * http://www.quirksmode.org/js/cookies.html */ function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function eraseCookie(name) { createCookie(name,"",-1); } /** * Forces a repaint (because WebKit has issues) * http://www.sitepoint.com/forums/showthread.php?p=4538763 * http://www.phpied.com/the-new-game-show-will-it-reflow/ */ function forceRepaint() { var ss = document.styleSheets[0]; try { ss.addRule('.xxxxxx', 'position: relative'); ss.removeRule(ss.rules.length - 1); } catch(e){} } \ No newline at end of file
dotjay/hashgrid
2cdf177395c26772e6f3126518883dd2f292a120
Updating link to github hosted version of the script. Note to anybody linking the master branch on their sites: the master branch *will* break as the script gets updated.
diff --git a/index.htm b/index.htm index 546f60e..33fa91f 100644 --- a/index.htm +++ b/index.htm @@ -1,375 +1,375 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>#grid</title> <style type="text/css"> /* Putting inline rules here so the document can be downloaded with style */ body{ font-size: 1em; line-height: 1.25; font-family: Arial, sans-serif; background: White; color: DimGray; margin: 0; padding: 0 20px; } #content{ font-size: 16px; line-height: 20px; position: relative; } #content{ width: 620px; margin: 0 auto; } #footer{ border-top: 1px dotted DarkGray; padding-top: 19px; } h1, h2{ color: Black; font-weight: normal; } h1{ font-size: 36px; line-height: 40px; margin: 40px 0 20px; padding-bottom: 19px; border-bottom: 1px dotted DarkGray; } h1 em{ font-style: normal; color: DarkGray; font-size: 16px; line-height: 20px; margin: 0 0 20px; } h2, h3{ font-size: 16px; font-weight: 700; line-height: 20px; margin: 0 0 20px; } h3{ font-weight: 300; } a:link, a:visited{ color: Black; text-decoration: none; padding: 0 2px; background-color: WhiteSmoke; border-bottom: 1px solid Gold; } a:focus{ outline: none; } a:focus, a:hover, a:active{ background-color: Khaki; border-bottom: 1px solid GoldenRod; } p, ul{ padding: 0; margin: 0 0 20px; } dl, ol{ padding: 0; margin: 0; } ul{ list-style: circle; } ol li{ margin-bottom: 20px; } dd{ margin: 0 0 20px 0; } del{ text-decoration: line-through; opacity: 0.75; } ins{ text-decoration: none; } code{ font-size: 14px; line-height: 1; } textarea{ font-family: 'Courier New', monospace; font-size: 14px; line-height: 20px; display: block; width: 600px; margin: 0 0 20px; padding: 0 0 0 15px; border: 0; color: Black; background: Gainsboro; border-left: 5px solid DarkGray; } #javascript-code{ height: 180px; } #css-code{ height: 1300px; } .summary em{ font-style: normal; position: absolute; color: DarkGray; right: 0; top: 18px; width: 140px; } .summary em span{ position: absolute; left: -9999px; } #download{ line-height: 60px; padding: 0 40px 0 15px; border-left: 5px solid DarkGray; background: Gainsboro; color: DimGray; } span.key{ color: Black; text-transform: uppercase; } </style> <!-- Set styles --> <style type="text/css"> /** * Grid */ #grid{ /* Vertical grid lines */ background: url(bg-grid-980.gif) repeat-y 0 0; /* Dimensions - same width as your grid with gutters */ width: 980px; /* Grid (left-aligned) position: absolute; top: 0; left: 0; */ /* Grid (centered) */ position: absolute; top: 0; left: 50%; margin-left: -490px; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option in the hashgrid.js file. */ #grid.grid-1{ /* Vertical grid lines for grid 1 */ background: url(bg-grid-980.gif) repeat-y 0 0; } #grid.grid-2{ /* Vertical grid lines for grid 2 */ background: url(bg-grid-660.gif) repeat-y 160px 0; /* Adjustments */ padding: 0 160px; width: 660px; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ #grid div.horiz{ /* 20px line height */ height: 19px; border-bottom: 1px dotted #aaa; margin: 0; padding: 0; } </style> </head> <body> <div id="content" role="main"> <h1>#grid <em>v4</em></h1> <p class="summary"><em>Mon, 29 Mar 2010<span>:</span></em> This is a little tool we created for our <a href="http://analog.coop/">Analog&#160;holding&#160;page</a>. It inserts a <a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a> in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit <span class="key">G</span> on your keyboard.</p> <h2>Download</h2> <p id="download"><a href="http://github.com/dotjay/hashgrid/downloads">Download #grid</a> from <a href="http://github.com/dotjay/hashgrid">GitHub</a></p> <h2 id="features">Features</h2> <ul> <li>Adaptable for all layout widths and alignments</li> <li>Adaptable for any vertical rhythm value</li> <li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li> <li>Uses a single JavaScript file, a little CSS, and an image (for the vertical lines)</li> </ul> <p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p> <h2 id="installation">Installation</h2> <ol> -<li><h3>Copy the <a href="http://github.com/dotjay/hashgrid/blob/master/hashgrid.js">hashgrid.js</a> script to your project</h3></li> +<li><h3>Copy the <a href="http://github.com/dotjay/hashgrid/blob/v4/hashgrid.js">hashgrid.js</a> script to your project</h3></li> <li><h3>Add the script to your page(s) just inside the <code>&#60;/body&#62;</code> tag</h3> <textarea id="javascript-code" cols="68" rows="8" readonly="readonly"> &#60;!-- Grab latest version of jQuery --&#62; &#60;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"&#62; &#60;/script&#62; &#60;!-- Include the hashgrid script --&#62; &#60;script type="text/javascript" src="hashgrid.js"&#62;&#60;/script&#62;</textarea></li> <li><h3>Add the CSS to your page(s)</h3> <textarea id="css-code" cols="68" rows="64" readonly="readonly"> /** * Grid */ #grid{ /* Vertical grid lines */ background: url(bg-grid-980.gif) repeat-y 0 0; /* Dimensions - same width as your grid with gutters */ width: 980px; /* Grid (left-aligned) position: absolute; top: 0; left: 0; */ /* Grid (centered) */ position: absolute; top: 0; left: 50%; margin-left: -490px; } /** * Classes for multiple grids * * When using more than one grid, remember to set the numberOfGrids * option in the hashgrid.js file. */ #grid.grid-1{ /* Vertical grid lines for grid 1 */ background: url(bg-grid-980.gif) repeat-y 0 0; } #grid.grid-2{ /* Vertical grid lines for grid 2 */ background: url(bg-grid-660.gif) repeat-y 160px 0; /* Adjustments */ padding: 0 160px; width: 660px; } /** * Horizontal grid lines, defined by your base line height * * Remember, the CSS properties that define the box model: * visible height = height + borders + margins + padding */ #grid div.horiz{ /* 20px line height */ height: 19px; border-bottom: 1px dotted #aaa; margin: 0; padding: 0; } </textarea></li> <li><h3>Modify #grid to suit your needs</h3> <p>The CSS and JavaScript is annotated to help you. We&#8217;ve included a <a href="bg-grid-980.gif">980px-wide background image</a> to provide the vertical grid lines (a 940-pixel-wide content area with 20px gutters). If you&#8217;re working to a <a href="http://www.markboulton.co.uk/journal/comments/five-simple-steps-to-designing-grid-systems-part-1">different grid</a>, you will need to create a new image for your guides. Don&#8217;t forget to make the background transparent!</p></li> </ol> <h2 id="usage">Usage</h2> <p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p> <dl> <dt><span class="key">G</span></dt> <dd>Show the grid until you release.</dd> <dt><span class="key">G</span> + <span class="key">H</span></dt> <dd>Show and hold the grid (<span class="key">G</span> will remove it again).</dd> <dt><span class="key">G</span> + <span class="key">F</span></dt> <dd>Toggle the grid to the foreground and back. Pressing <span class="key">F</span> while the grid is held also works.</dd> <dt><span class="key">G</span> + <span class="key">J</span></dt> <dd>Jump to the next grid. Pressing <span class="key">J</span> while the grid is held also works.</dd> </dl> <p><em>N.B. A cookie conveniently remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em></p> <h2 id="release-notes">Release Notes</h2> <dl> <dt>v4&#8201;&#8212;&#8201;29 Mar 2010</dt> <dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd> <dt>v3&#8201;&#8212;&#8201;22 Feb 2010</dt> <dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd> <dt>v2&#8201;&#8212;&#8201;2 Feb 2010</dt> <dd>Keys are now more easily configured (see top of hashgrid.js). Renamed the GridOverlay object to hashgrid. Fixed crash when using with disabled CSS.</dd> <dt>v1&#8201;&#8212;&#8201;21 Dec 2009</dt> <dd>First release.</dd> </dl> <h2 id="known-issues">Known Issues</h2> <ul> <li><del>IE 8: Fully functional, but the default <span class="key">ALT</span> + <span class="key">G</span> + <span class="key">ENTER</span> shortcut puts IE into full screen mode. Hit <span class="key">ALT</span> + <span class="key">ENTER</span> to toggle full screen mode off again.</del><ins datetime="2010-02-22"> The default keyboard shortcuts have been changed.</ins></li> <li>IE 6: The grid is always in the foreground.</li> <li>Opera 9/10: Using <span class="key">CTRL</span> or <span class="key">ALT</span> as a modifier key will not work due to different key handling by the browser.</li> </ul> <h2 id="license">License</h2> <p>Released under a <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike License</a>, which essentially means that you&#8217;re free to copy it and adapt it. <a href="http://analog.coop/#talk-to-us">Contact us at Analog</a> if you need a different license.</p> <div id="footer" role="contentinfo"> <p>#grid is an <a href="http://analog.coop/">Analog</a> gig. It was conceived by <a href="http://jontangerine.com/">Jon Tan</a>, and built by <a href="http://accessibility.co.uk/">Jon Gibbins</a>, in cahoots with our <a href="http://analog.coop#is">fine friends</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p> </div> </div> <!-- Grab latest version of jQuery --> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <!-- Include the hashgrid script --> <script type="text/javascript" src="hashgrid.js"></script> </body> </html>
dotjay/hashgrid
ced4693d497673bf75e09690f2ed0d1d4592cdea
can't calculate the number of vertical divs in Safari and Chrome (margin assumes the rest of the block), so solving this with brute force.
diff --git a/hashgrid.js b/hashgrid.js index a365a79..d59a33e 100644 --- a/hashgrid.js +++ b/hashgrid.js @@ -1,332 +1,323 @@ /** * hashgrid (jQuery version) * http://github.com/dotjay/hashgrid * Version 4, 29 Mar 2010 * By Jon Gibbins, accessibility.co.uk * * // Using a basic #grid setup * var grid = new hashgrid(); * * // Using #grid with a custom id (e.g. #mygrid) * var grid = new hashgrid("mygrid"); * * // Using #grid with additional options * var grid = new hashgrid({ * id: 'mygrid', // id for the grid container * modifierKey: 'alt', // optional 'ctrl', 'alt' or 'shift' * showGridKey: 's', // key to show the grid * holdGridKey: 'enter', // key to hold the grid in place * foregroundKey: 'f', // key to toggle foreground/background * jumpGridsKey: 'd', // key to cycle through the grid classes * numberOfGrids: 2, // number of grid classes used * classPrefix: 'class', // prefix for the grid classes * cookiePrefix: 'mygrid' // prefix for the cookie name * }); */ /** * You can call hashgrid from your own code, but it's loaded here by * default for convenience. */ $(document).ready(function() { var grid = new hashgrid({ numberOfGrids: 2 }); }); /** * hashgrid overlay */ var hashgrid = function(set) { var options = { id: 'grid', // id for the grid container modifierKey: null, // optional 'ctrl', 'alt' or 'shift' showGridKey: 'g', // key to show the grid holdGridKey: 'h', // key to hold the grid in place foregroundKey: 'f', // key to toggle foreground/background jumpGridsKey: 'j', // key to cycle through the grid classes numberOfGrids: 1, // number of grid classes used classPrefix: 'grid-', // prefix for the grid classes cookiePrefix: 'hashgrid'// prefix for the cookie name }; var overlayOn = false, sticky = false, overlayZState = 'B', overlayZBackground = -1, overlayZForeground = 9999, classNumber = 1; // Apply options if (typeof set == 'object') { var k; for (k in set) options[k] = set[k]; } else if (typeof set == 'string') { options.id = set; } // Remove any conflicting overlay if ($('#' + options.id).length > 0) { $('#' + options.id).remove(); } // Create overlay, hidden before adding to DOM var overlayEl = $('<div></div>'); overlayEl .attr('id', options.id) .css({ display: 'none', 'pointer-events': 'none' }); $("body").prepend(overlayEl); var overlay = $('#' + options.id); // Unless a custom z-index is set, ensure the overlay will be behind everything if (overlay.css('z-index') == 'auto') overlay.css('z-index', overlayZBackground); // Override the default overlay height with the actual page height var pageHeight = parseFloat($(document).height()); overlay.height(pageHeight); // Add the first grid line so that we can measure it overlay.append('<div class="horiz first-line">'); // Calculate the number of grid lines needed var overlayGridLines = overlay.children('.horiz'), overlayGridLineHeight = parseFloat(overlayGridLines.css('height')) + parseFloat(overlayGridLines.css('border-bottom-width')); // Break on zero line height if (overlayGridLineHeight <= 0) return true; // Add the remaining grid lines var i, numGridLines = Math.floor(pageHeight / overlayGridLineHeight); for (i = numGridLines - 1; i >= 1; i--) { overlay.append('<div class="horiz"></div>'); } // vertical grid overlay.append($('<div class="vert-container"></div>')); var overlayVert = overlay.children('.vert-container'); var gridWidth = overlay.width(); overlayVert.css({width: gridWidth, position: 'absolute', top: 0}); - overlayVert.append('<div class="vert">&nbsp;</div>'); + overlayVert.append('<div class="vert first-line">&nbsp;</div>'); - var overlayGridLines = overlayVert.children('.vert'); - // need to temporarily set this to display: block to get the size - overlay.css({visibility: 'hidden', display: 'block'}); - var overlayGridLinesWidth = overlayGridLines.outerWidth(true); - overlay.css({visibility: 'inherit', display: 'none'}); - overlayGridLines.addClass('first-line'); - - numGridLines = Math.floor(gridWidth / overlayGridLinesWidth); - - // multiply this by two to make sure we have enough lines - // (we *could* still run out) - for (i = 0; i < numGridLines * 2; i++) { + // 30 is an arbitrarily large number... + // can't calculate the margin width properly + for (i = 0; i < 30; i++) { overlayVert.append('<div class="vert">&nbsp;</div>'); } overlayVert.children() .height(pageHeight) .css({display: 'inline-block'}); // Check for saved state var overlayCookie = readCookie(options.cookiePrefix + options.id); if (typeof overlayCookie == 'string') { var state = overlayCookie.split(','); state[2] = Number(state[2]); if ((typeof state[2] == 'number') && !isNaN(state[2])) { classNumber = state[2].toFixed(0); overlay.addClass(options.classPrefix + classNumber); } if (state[1] == 'F') { overlayZState = 'F'; overlay.css('z-index', overlayZForeground); } if (state[0] == '1') { overlayOn = true; sticky = true; showOverlay(); } } else { overlay.addClass(options.classPrefix + classNumber); } // Keyboard controls $(document).bind('keydown', keydownHandler); $(document).bind('keyup', keyupHandler); /** * Helpers */ function getModifier(e) { if (options.modifierKey == null) return true; // Bypass by default var m = true; switch(options.modifierKey) { case 'ctrl': m = (e.ctrlKey ? e.ctrlKey : false); break; case 'alt': m = (e.altKey ? e.altKey : false); break; case 'shift': m = (e.shiftKey ? e.shiftKey : false); break; } return m; } function getKey(e) { var k = false, c = (e.keyCode ? e.keyCode : e.which); // Handle keywords if (c == 13) k = 'enter'; // Handle letters else k = String.fromCharCode(c).toLowerCase(); return k; } function saveState() { createCookie(options.cookiePrefix + options.id, (sticky ? '1' : '0') + ',' + overlayZState + ',' + classNumber, 1); } function showOverlay() { overlay.show(); overlayVert.css({width: overlay.width()}); // hide any vertical blocks that aren't at the top of the viewport overlayVert.children('.vert').each(function () { $(this).css('display','inline-block'); if ($(this).offset().top > 0) { $(this).hide(); } }); } /** * Event handlers */ function keydownHandler(e) { var source = e.target.tagName.toLowerCase(); if ((source == 'input') || (source == 'textarea') || (source == 'select')) return true; var m = getModifier(e); if (!m) return true; var k = getKey(e); if (!k) return true; switch(k) { case options.showGridKey: if (!overlayOn) { showOverlay(); overlayOn = true; } else if (sticky) { overlay.hide(); overlayOn = false; sticky = false; saveState(); } break; case options.holdGridKey: if (overlayOn && !sticky) { // Turn sticky overlay on sticky = true; saveState(); } break; case options.foregroundKey: if (overlayOn) { // Toggle sticky overlay z-index if (overlay.css('z-index') == overlayZForeground) { overlay.css('z-index', overlayZBackground); overlayZState = 'B'; } else { overlay.css('z-index', overlayZForeground); overlayZState = 'F'; } saveState(); } break; case options.jumpGridsKey: if (overlayOn && (options.numberOfGrids > 1)) { // Cycle through the available grids overlay.removeClass(options.classPrefix + classNumber); classNumber++; if (classNumber > options.numberOfGrids) classNumber = 1; overlay.addClass(options.classPrefix + classNumber); showOverlay(); if (/webkit/.test( navigator.userAgent.toLowerCase() )) { forceRepaint(); } saveState(); } break; } } function keyupHandler(e) { var m = getModifier(e); if (!m) return true; var k = getKey(e); if (!k) return true; if ((k == options.showGridKey) && !sticky) { overlay.hide(); overlayOn = false; } } } /** * Cookie functions * * By Peter-Paul Koch: * http://www.quirksmode.org/js/cookies.html */ function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function eraseCookie(name) { createCookie(name,"",-1); } /** * Forces a repaint (because WebKit has issues) * http://www.sitepoint.com/forums/showthread.php?p=4538763 * http://www.phpied.com/the-new-game-show-will-it-reflow/ */ function forceRepaint() { var ss = document.styleSheets[0]; try { ss.addRule('.xxxxxx', 'position: relative'); ss.removeRule(ss.rules.length - 1); } catch(e){} }
dotjay/hashgrid
612299128a4e45ea9e388ed4c6fa5ab9c31ece72
honour color keyword trick (-:
diff --git a/README.md b/README.md new file mode 100644 index 0000000..c4326c7 --- /dev/null +++ b/README.md @@ -0,0 +1,14 @@ +#grid +===== + +A little tool that inserts a layout grid in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. + +Features +-------- + + * Adaptable for all layout widths and alignments + * Adaptable for any vertical rhythm value + * Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids + * Uses a single JavaScript file, and a little CSS + +Notes on installation and usage can be found in the included index.htm file. diff --git a/bg-grid-660.gif b/bg-grid-660.gif new file mode 100755 index 0000000..0418c18 Binary files /dev/null and b/bg-grid-660.gif differ diff --git a/bg-grid-980.gif b/bg-grid-980.gif new file mode 100644 index 0000000..a4a8c01 Binary files /dev/null and b/bg-grid-980.gif differ diff --git a/hashgrid.js b/hashgrid.js new file mode 100644 index 0000000..a365a79 --- /dev/null +++ b/hashgrid.js @@ -0,0 +1,332 @@ +/** + * hashgrid (jQuery version) + * http://github.com/dotjay/hashgrid + * Version 4, 29 Mar 2010 + * By Jon Gibbins, accessibility.co.uk + * + * // Using a basic #grid setup + * var grid = new hashgrid(); + * + * // Using #grid with a custom id (e.g. #mygrid) + * var grid = new hashgrid("mygrid"); + * + * // Using #grid with additional options + * var grid = new hashgrid({ + * id: 'mygrid', // id for the grid container + * modifierKey: 'alt', // optional 'ctrl', 'alt' or 'shift' + * showGridKey: 's', // key to show the grid + * holdGridKey: 'enter', // key to hold the grid in place + * foregroundKey: 'f', // key to toggle foreground/background + * jumpGridsKey: 'd', // key to cycle through the grid classes + * numberOfGrids: 2, // number of grid classes used + * classPrefix: 'class', // prefix for the grid classes + * cookiePrefix: 'mygrid' // prefix for the cookie name + * }); + */ + + +/** + * You can call hashgrid from your own code, but it's loaded here by + * default for convenience. + */ +$(document).ready(function() { + + var grid = new hashgrid({ + numberOfGrids: 2 + }); + +}); + + +/** + * hashgrid overlay + */ +var hashgrid = function(set) { + + var options = { + id: 'grid', // id for the grid container + modifierKey: null, // optional 'ctrl', 'alt' or 'shift' + showGridKey: 'g', // key to show the grid + holdGridKey: 'h', // key to hold the grid in place + foregroundKey: 'f', // key to toggle foreground/background + jumpGridsKey: 'j', // key to cycle through the grid classes + numberOfGrids: 1, // number of grid classes used + classPrefix: 'grid-', // prefix for the grid classes + cookiePrefix: 'hashgrid'// prefix for the cookie name + }; + var overlayOn = false, + sticky = false, + overlayZState = 'B', + overlayZBackground = -1, + overlayZForeground = 9999, + classNumber = 1; + + // Apply options + if (typeof set == 'object') { + var k; + for (k in set) options[k] = set[k]; + } + else if (typeof set == 'string') { + options.id = set; + } + + // Remove any conflicting overlay + if ($('#' + options.id).length > 0) { + $('#' + options.id).remove(); + } + + // Create overlay, hidden before adding to DOM + var overlayEl = $('<div></div>'); + overlayEl + .attr('id', options.id) + .css({ + display: 'none', + 'pointer-events': 'none' + }); + $("body").prepend(overlayEl); + var overlay = $('#' + options.id); + + // Unless a custom z-index is set, ensure the overlay will be behind everything + if (overlay.css('z-index') == 'auto') overlay.css('z-index', overlayZBackground); + + // Override the default overlay height with the actual page height + var pageHeight = parseFloat($(document).height()); + overlay.height(pageHeight); + + // Add the first grid line so that we can measure it + overlay.append('<div class="horiz first-line">'); + + // Calculate the number of grid lines needed + var overlayGridLines = overlay.children('.horiz'), + overlayGridLineHeight = parseFloat(overlayGridLines.css('height')) + parseFloat(overlayGridLines.css('border-bottom-width')); + + // Break on zero line height + if (overlayGridLineHeight <= 0) return true; + + // Add the remaining grid lines + var i, numGridLines = Math.floor(pageHeight / overlayGridLineHeight); + for (i = numGridLines - 1; i >= 1; i--) { + overlay.append('<div class="horiz"></div>'); + } + + // vertical grid + overlay.append($('<div class="vert-container"></div>')); + var overlayVert = overlay.children('.vert-container'); + var gridWidth = overlay.width(); + overlayVert.css({width: gridWidth, position: 'absolute', top: 0}); + overlayVert.append('<div class="vert">&nbsp;</div>'); + + var overlayGridLines = overlayVert.children('.vert'); + // need to temporarily set this to display: block to get the size + overlay.css({visibility: 'hidden', display: 'block'}); + var overlayGridLinesWidth = overlayGridLines.outerWidth(true); + overlay.css({visibility: 'inherit', display: 'none'}); + overlayGridLines.addClass('first-line'); + + numGridLines = Math.floor(gridWidth / overlayGridLinesWidth); + + // multiply this by two to make sure we have enough lines + // (we *could* still run out) + for (i = 0; i < numGridLines * 2; i++) { + overlayVert.append('<div class="vert">&nbsp;</div>'); + } + + overlayVert.children() + .height(pageHeight) + .css({display: 'inline-block'}); + + // Check for saved state + var overlayCookie = readCookie(options.cookiePrefix + options.id); + if (typeof overlayCookie == 'string') { + var state = overlayCookie.split(','); + state[2] = Number(state[2]); + if ((typeof state[2] == 'number') && !isNaN(state[2])) { + classNumber = state[2].toFixed(0); + overlay.addClass(options.classPrefix + classNumber); + } + if (state[1] == 'F') { + overlayZState = 'F'; + overlay.css('z-index', overlayZForeground); + } + if (state[0] == '1') { + overlayOn = true; + sticky = true; + showOverlay(); + } + } + else { + overlay.addClass(options.classPrefix + classNumber); + } + + // Keyboard controls + $(document).bind('keydown', keydownHandler); + $(document).bind('keyup', keyupHandler); + + /** + * Helpers + */ + + function getModifier(e) { + if (options.modifierKey == null) return true; // Bypass by default + var m = true; + switch(options.modifierKey) { + case 'ctrl': + m = (e.ctrlKey ? e.ctrlKey : false); + break; + + case 'alt': + m = (e.altKey ? e.altKey : false); + break; + + case 'shift': + m = (e.shiftKey ? e.shiftKey : false); + break; + } + return m; + } + + function getKey(e) { + var k = false, c = (e.keyCode ? e.keyCode : e.which); + // Handle keywords + if (c == 13) k = 'enter'; + // Handle letters + else k = String.fromCharCode(c).toLowerCase(); + return k; + } + + function saveState() { + createCookie(options.cookiePrefix + options.id, (sticky ? '1' : '0') + ',' + overlayZState + ',' + classNumber, 1); + } + + function showOverlay() { + overlay.show(); + overlayVert.css({width: overlay.width()}); + // hide any vertical blocks that aren't at the top of the viewport + overlayVert.children('.vert').each(function () { + $(this).css('display','inline-block'); + if ($(this).offset().top > 0) { + $(this).hide(); + } + }); + } + + /** + * Event handlers + */ + + function keydownHandler(e) { + var source = e.target.tagName.toLowerCase(); + if ((source == 'input') || (source == 'textarea') || (source == 'select')) return true; + var m = getModifier(e); + if (!m) return true; + var k = getKey(e); + if (!k) return true; + switch(k) { + case options.showGridKey: + if (!overlayOn) { + showOverlay(); + overlayOn = true; + } + else if (sticky) { + overlay.hide(); + overlayOn = false; + sticky = false; + saveState(); + } + break; + case options.holdGridKey: + if (overlayOn && !sticky) { + // Turn sticky overlay on + sticky = true; + saveState(); + } + break; + case options.foregroundKey: + if (overlayOn) { + // Toggle sticky overlay z-index + if (overlay.css('z-index') == overlayZForeground) { + overlay.css('z-index', overlayZBackground); + overlayZState = 'B'; + } + else { + overlay.css('z-index', overlayZForeground); + overlayZState = 'F'; + } + saveState(); + } + break; + case options.jumpGridsKey: + if (overlayOn && (options.numberOfGrids > 1)) { + // Cycle through the available grids + overlay.removeClass(options.classPrefix + classNumber); + classNumber++; + if (classNumber > options.numberOfGrids) classNumber = 1; + overlay.addClass(options.classPrefix + classNumber); + showOverlay(); + if (/webkit/.test( navigator.userAgent.toLowerCase() )) { + forceRepaint(); + } + saveState(); + } + break; + } + } + + function keyupHandler(e) { + var m = getModifier(e); + if (!m) return true; + var k = getKey(e); + if (!k) return true; + if ((k == options.showGridKey) && !sticky) { + overlay.hide(); + overlayOn = false; + } + } + +} + + +/** + * Cookie functions + * + * By Peter-Paul Koch: + * http://www.quirksmode.org/js/cookies.html + */ +function createCookie(name,value,days) { + if (days) { + var date = new Date(); + date.setTime(date.getTime()+(days*24*60*60*1000)); + var expires = "; expires="+date.toGMTString(); + } + else var expires = ""; + document.cookie = name+"="+value+expires+"; path=/"; +} + +function readCookie(name) { + var nameEQ = name + "="; + var ca = document.cookie.split(';'); + for(var i=0;i < ca.length;i++) { + var c = ca[i]; + while (c.charAt(0)==' ') c = c.substring(1,c.length); + if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); + } + return null; +} + +function eraseCookie(name) { + createCookie(name,"",-1); +} + + +/** + * Forces a repaint (because WebKit has issues) + * http://www.sitepoint.com/forums/showthread.php?p=4538763 + * http://www.phpied.com/the-new-game-show-will-it-reflow/ + */ +function forceRepaint() { + var ss = document.styleSheets[0]; + try { + ss.addRule('.xxxxxx', 'position: relative'); + ss.removeRule(ss.rules.length - 1); + } catch(e){} +} diff --git a/index.htm b/index.htm new file mode 100644 index 0000000..5714a11 --- /dev/null +++ b/index.htm @@ -0,0 +1,388 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> +<html lang="en"> + +<head> +<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> +<title>#grid</title> + +<style type="text/css"> + +/* Putting inline rules here so the document can be downloaded with style */ + +body{ +font-size: 1em; +line-height: 1.25; +font-family: Arial, sans-serif; +background: White; +color: DimGray; +margin: 0; +padding: 0 20px; +} +#content{ +font-size: 16px; +line-height: 20px; +position: relative; +} +#content{ +width: 620px; +margin: 0 auto; +} +#footer{ +border-top: 1px dotted DarkGray; +padding-top: 19px; +} +h1, h2{ +color: Black; +font-weight: normal; +} +h1{ +font-size: 36px; +line-height: 40px; +margin: 40px 0 20px; +padding-bottom: 19px; +border-bottom: 1px dotted DarkGray; +} +h1 em{ +font-style: normal; +color: DarkGray; +font-size: 16px; +line-height: 20px; +margin: 0 0 20px; +} +h2, h3{ +font-size: 16px; +font-weight: 700; +line-height: 20px; +margin: 0 0 20px; +} +h3{ +font-weight: 300; +} +a:link, +a:visited{ +color: Black; +text-decoration: none; +padding: 0 2px; +background-color: WhiteSmoke; +border-bottom: 1px solid Gold; +} +a:focus{ +outline: none; +} +a:focus, +a:hover, +a:active{ +background-color: Khaki; +border-bottom: 1px solid GoldenRod; +} +p, ul{ +padding: 0; +margin: 0 0 20px; +} +dl, ol{ +padding: 0; +margin: 0; +} +ul{ +list-style: circle; +} +ol li{ +margin-bottom: 20px; +} +dd{ +margin: 0 0 20px 0; +} +del{ +text-decoration: line-through; +opacity: 0.75; +} +ins{ +text-decoration: none; +} +code{ +font-size: 14px; +line-height: 1; +} +textarea{ +font-family: 'Courier New', monospace; +font-size: 14px; +line-height: 20px; +display: block; +width: 600px; +margin: 0 0 20px; +padding: 0 0 0 15px; +border: 0; +color: Black; +background: Gainsboro; +border-left: 5px solid DarkGray; +} +#javascript-code{ +height: 180px; +} +#css-code{ +height: 1300px; +} +.summary em{ +font-style: normal; +position: absolute; +color: DarkGray; +right: 0; +top: 18px; +width: 140px; +} +.summary em span{ +position: absolute; +left: -9999px; +} +#download{ +line-height: 60px; +padding: 0 40px 0 15px; +border-left: 5px solid DarkGray; +background: Gainsboro; +color: DimGray; +} +span.key{ +color: Black; +text-transform: uppercase; +} +</style> + +<!-- Set styles --> +<style type="text/css"> + +/** + * Grid + */ +#grid{ + + /* Dimensions - same width as your grid with gutters */ + width: 980px; + + /* Grid (left-aligned) + position: absolute; + top: 0; + left: 0; + */ + + /* Grid (centered) */ + position: absolute; + top: 0; + left: 50%; + margin-left: -490px; + +} + +/** + * Classes for vertical grids + */ +#grid div.vert { + margin-right: 20px; + width: 138px; + border: 1px dashed darkgray; + border-width: 0 1px; +} + +#grid div.vert.first-line { + margin-left: 20px; +} + +/** +* Classes for multiple grids +* +* When using more than one grid, remember to set the numberOfGrids +* option in the hashgrid.js file. +*/ +#grid.grid-1 div.vert { + border-color: green; +} +#grid.grid-2 div.vert { + border-color: red; +} +#grid.grid-2 { + /* Adjustments */ + padding: 0 160px; + width: 660px; +} + + +/** + * Horizontal grid lines, defined by your base line height + * + * Remember, the CSS properties that define the box model: + * visible height = height + borders + margins + padding + */ +#grid div.horiz{ + + /* 20px line height */ + height: 19px; + border-bottom: 1px dotted darkgray; + margin: 0; + padding: 0; + +} + +</style> + +</head> + +<body> + +<div id="content" role="main"> + +<h1>#grid <em>v4</em></h1> + +<p class="summary"><em>Mon, 29 Mar 2010<span>:</span></em> This is a little tool we created for our <a href="http://analog.coop/">Analog&#160;holding&#160;page</a>. It inserts a <a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a> in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit <span class="key">G</span> on your keyboard.</p> + +<h2>Download</h2> +<p id="download"><a href="http://github.com/dotjay/hashgrid/downloads">Download #grid</a> from <a href="http://github.com/dotjay/hashgrid">GitHub</a></p> + +<h2 id="features">Features</h2> +<ul> +<li>Adaptable for all layout widths and alignments</li> +<li>Adaptable for any vertical rhythm value</li> +<li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li> +<li>Uses a single JavaScript file, a little CSS</li> +</ul> +<p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p> + +<h2 id="installation">Installation</h2> +<ol> +<li><h3>Copy the <a href="http://github.com/dotjay/hashgrid/blob/master/hashgrid.js">hashgrid.js</a> script to your project</h3></li> +<li><h3>Add the script to your page(s) just inside the <code>&#60;/body&#62;</code> tag</h3> +<textarea id="javascript-code" cols="68" rows="8" readonly="readonly"> + +&#60;!-- Grab latest version of jQuery --&#62; +&#60;script type="text/javascript" + src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"&#62; +&#60;/script&#62; + +&#60;!-- Include the hashgrid script --&#62; +&#60;script type="text/javascript" src="hashgrid.js"&#62;&#60;/script&#62;</textarea></li> +<li><h3>Add the CSS to your page(s)</h3> +<textarea id="css-code" cols="68" rows="64" readonly="readonly"> + +/** + * Grid + */ +#grid{ + + /* Dimensions - same width as your grid with gutters */ + width: 980px; + + /* Grid (left-aligned) + position: absolute; + top: 0; + left: 0; + */ + + /* Grid (centered) */ + position: absolute; + top: 0; + left: 50%; + margin-left: -490px; + +} + +/** + * Classes for vertical grids + */ +#grid div.vert { + margin-right: 20px; + width: 138px; + border: 1px dashed darkgray; + border-width: 0 1px; +} + +#grid div.vert.first-line { + margin-left: 20px; +} + +/** +* Classes for multiple grids +* +* When using more than one grid, remember to set the numberOfGrids +* option in the hashgrid.js file. +*/ +#grid.grid-1 div.vert { + border-color: green; +} +#grid.grid-2 div.vert { + border-color: red; +} +#grid.grid-2 { + /* Adjustments */ + padding: 0 160px; + width: 660px; +} + +/** + * Horizontal grid lines, defined by your base line height + * + * Remember, the CSS properties that define the box model: + * visible height = height + borders + margins + padding + */ +#grid div.horiz{ + + /* 20px line height */ + height: 19px; + border-bottom: 1px dotted darkgray; + margin: 0; + padding: 0; + +} +</textarea></li> +<li><h3>Modify #grid to suit your needs</h3> +<p>The CSS and JavaScript is annotated to help you.</p></li> +</ol> + +<h2 id="usage">Usage</h2> +<p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p> +<dl> +<dt><span class="key">G</span></dt> +<dd>Show the grid until you release.</dd> +<dt><span class="key">G</span> + <span class="key">H</span></dt> +<dd>Show and hold the grid (<span class="key">G</span> will remove it again).</dd> +<dt><span class="key">G</span> + <span class="key">F</span></dt> +<dd>Toggle the grid to the foreground and back. Pressing <span class="key">F</span> while the grid is held also works.</dd> +<dt><span class="key">G</span> + <span class="key">J</span></dt> +<dd>Jump to the next grid. Pressing <span class="key">J</span> while the grid is held also works.</dd> +</dl> +<p><em>N.B. A cookie conveniently remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em></p> + +<h2 id="release-notes">Release Notes</h2> +<dl> +<dt>v4&#8201;&#8212;&#8201;29 Mar 2010</dt> +<dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd> +<dt>v3&#8201;&#8212;&#8201;22 Feb 2010</dt> +<dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd> +<dt>v2&#8201;&#8212;&#8201;2 Feb 2010</dt> +<dd>Keys are now more easily configured (see top of hashgrid.js). Renamed the GridOverlay object to hashgrid. Fixed crash when using with disabled CSS.</dd> +<dt>v1&#8201;&#8212;&#8201;21 Dec 2009</dt> +<dd>First release.</dd> +</dl> + +<h2 id="known-issues">Known Issues</h2> +<ul> +<li><del>IE 8: Fully functional, but the default <span class="key">ALT</span> + <span class="key">G</span> + <span class="key">ENTER</span> shortcut puts IE into full screen mode. Hit <span class="key">ALT</span> + <span class="key">ENTER</span> to toggle full screen mode off again.</del><ins datetime="2010-02-22"> The default keyboard shortcuts have been changed.</ins></li> +<li>IE 6: The grid is always in the foreground.</li> +<li>Opera 9/10: Using <span class="key">CTRL</span> or <span class="key">ALT</span> as a modifier key will not work due to different key handling by the browser.</li> +</ul> + +<h2 id="license">License</h2> +<p>Released under a <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike License</a>, which essentially means that you&#8217;re free to copy it and adapt it. <a href="http://analog.coop/#talk-to-us">Contact us at Analog</a> if you need a different license.</p> + +<div id="footer" role="contentinfo"> +<p>#grid is an <a href="http://analog.coop/">Analog</a> gig. It was conceived by <a href="http://jontangerine.com/">Jon Tan</a>, and built by <a href="http://accessibility.co.uk/">Jon Gibbins</a>, in cahoots with our <a href="http://analog.coop#is">fine friends</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p> +</div> + +</div> + +<!-- Grab latest version of jQuery --> +<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> + +<!-- Include the hashgrid script --> +<script type="text/javascript" src="hashgrid.js"></script> + +</body> + +</html>
dotjay/hashgrid
7d274b7611a4468ecd2916f36929dce5bb7ebe67
Added pointer-events: none; to grid overlay to allow click-through to content when the grid is in the foreground in Firefox 3.6+, Chrome 4+, and Safari 4+.
diff --git a/README.md b/README.md new file mode 100644 index 0000000..820917a --- /dev/null +++ b/README.md @@ -0,0 +1,14 @@ +#grid +===== + +A little tool that inserts a layout grid in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. + +Features +-------- + + * Adaptable for all layout widths and alignments + * Adaptable for any vertical rhythm value + * Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids + * Uses a single JavaScript file, a little CSS, and an image (for the vertical lines) + +Notes on installation and usage can be found in the included index.htm file. diff --git a/bg-grid-660.gif b/bg-grid-660.gif new file mode 100755 index 0000000..0418c18 Binary files /dev/null and b/bg-grid-660.gif differ diff --git a/bg-grid-980.gif b/bg-grid-980.gif new file mode 100644 index 0000000..a4a8c01 Binary files /dev/null and b/bg-grid-980.gif differ diff --git a/hashgrid.js b/hashgrid.js new file mode 100644 index 0000000..7217c49 --- /dev/null +++ b/hashgrid.js @@ -0,0 +1,293 @@ +/** + * hashgrid (jQuery version) + * http://github.com/dotjay/hashgrid + * Version 4, 29 Mar 2010 + * By Jon Gibbins, accessibility.co.uk + * + * // Using a basic #grid setup + * var grid = new hashgrid(); + * + * // Using #grid with a custom id (e.g. #mygrid) + * var grid = new hashgrid("mygrid"); + * + * // Using #grid with additional options + * var grid = new hashgrid({ + * id: 'mygrid', // id for the grid container + * modifierKey: 'alt', // optional 'ctrl', 'alt' or 'shift' + * showGridKey: 's', // key to show the grid + * holdGridKey: 'enter', // key to hold the grid in place + * foregroundKey: 'f', // key to toggle foreground/background + * jumpGridsKey: 'd', // key to cycle through the grid classes + * numberOfGrids: 2, // number of grid classes used + * classPrefix: 'class', // prefix for the grid classes + * cookiePrefix: 'mygrid' // prefix for the cookie name + * }); + */ + + +/** + * You can call hashgrid from your own code, but it's loaded here by + * default for convenience. + */ +$(document).ready(function() { + + var grid = new hashgrid({ + numberOfGrids: 2 + }); + +}); + + +/** + * hashgrid overlay + */ +var hashgrid = function(set) { + + var options = { + id: 'grid', // id for the grid container + modifierKey: null, // optional 'ctrl', 'alt' or 'shift' + showGridKey: 'g', // key to show the grid + holdGridKey: 'h', // key to hold the grid in place + foregroundKey: 'f', // key to toggle foreground/background + jumpGridsKey: 'j', // key to cycle through the grid classes + numberOfGrids: 1, // number of grid classes used + classPrefix: 'grid-', // prefix for the grid classes + cookiePrefix: 'hashgrid'// prefix for the cookie name + }; + var overlayOn = false, + sticky = false, + overlayZState = 'B', + overlayZBackground = -1, + overlayZForeground = 9999, + classNumber = 1; + + // Apply options + if (typeof set == 'object') { + var k; + for (k in set) options[k] = set[k]; + } + else if (typeof set == 'string') { + options.id = set; + } + + // Remove any conflicting overlay + if ($('#' + options.id).length > 0) { + $('#' + options.id).remove(); + } + + // Create overlay, hidden before adding to DOM + var overlayEl = $('<div></div>'); + overlayEl + .attr('id', options.id) + .css({ + display: 'none', + 'pointer-events': 'none' + }); + $("body").prepend(overlayEl); + var overlay = $('#' + options.id); + + // Unless a custom z-index is set, ensure the overlay will be behind everything + if (overlay.css('z-index') == 'auto') overlay.css('z-index', overlayZBackground); + + // Override the default overlay height with the actual page height + var pageHeight = parseFloat($(document).height()); + overlay.height(pageHeight); + + // Add the first grid line so that we can measure it + overlay.append('<div class="horiz first-line">'); + + // Calculate the number of grid lines needed + var overlayGridLines = overlay.children('.horiz'), + overlayGridLineHeight = parseFloat(overlayGridLines.css('height')) + parseFloat(overlayGridLines.css('border-bottom-width')); + + // Break on zero line height + if (overlayGridLineHeight <= 0) return true; + + // Add the remaining grid lines + var i, numGridLines = Math.floor(pageHeight / overlayGridLineHeight); + for (i = numGridLines - 1; i >= 1; i--) { + overlay.append('<div class="horiz"></div>'); + } + + // Check for saved state + var overlayCookie = readCookie(options.cookiePrefix + options.id); + if (typeof overlayCookie == 'string') { + var state = overlayCookie.split(','); + state[2] = Number(state[2]); + if ((typeof state[2] == 'number') && !isNaN(state[2])) { + classNumber = state[2].toFixed(0); + overlay.addClass(options.classPrefix + classNumber); + } + if (state[1] == 'F') { + overlayZState = 'F'; + overlay.css('z-index', overlayZForeground); + } + if (state[0] == '1') { + overlayOn = true; + sticky = true; + overlay.show(); + } + } + else { + overlay.addClass(options.classPrefix + classNumber) + } + + // Keyboard controls + $(document).bind('keydown', keydownHandler); + $(document).bind('keyup', keyupHandler); + + /** + * Helpers + */ + + function getModifier(e) { + if (options.modifierKey == null) return true; // Bypass by default + var m = true; + switch(options.modifierKey) { + case 'ctrl': + m = (e.ctrlKey ? e.ctrlKey : false); + break; + + case 'alt': + m = (e.altKey ? e.altKey : false); + break; + + case 'shift': + m = (e.shiftKey ? e.shiftKey : false); + break; + } + return m; + } + + function getKey(e) { + var k = false, c = (e.keyCode ? e.keyCode : e.which); + // Handle keywords + if (c == 13) k = 'enter'; + // Handle letters + else k = String.fromCharCode(c).toLowerCase(); + return k; + } + + function saveState() { + createCookie(options.cookiePrefix + options.id, (sticky ? '1' : '0') + ',' + overlayZState + ',' + classNumber, 1); + } + + /** + * Event handlers + */ + + function keydownHandler(e) { + var source = e.target.tagName.toLowerCase(); + if ((source == 'input') || (source == 'textarea') || (source == 'select')) return true; + var m = getModifier(e); + if (!m) return true; + var k = getKey(e); + if (!k) return true; + switch(k) { + case options.showGridKey: + if (!overlayOn) { + overlay.show(); + overlayOn = true; + } + else if (sticky) { + overlay.hide(); + overlayOn = false; + sticky = false; + saveState(); + } + break; + case options.holdGridKey: + if (overlayOn && !sticky) { + // Turn sticky overlay on + sticky = true; + saveState(); + } + break; + case options.foregroundKey: + if (overlayOn) { + // Toggle sticky overlay z-index + if (overlay.css('z-index') == overlayZForeground) { + overlay.css('z-index', overlayZBackground); + overlayZState = 'B'; + } + else { + overlay.css('z-index', overlayZForeground); + overlayZState = 'F'; + } + saveState(); + } + break; + case options.jumpGridsKey: + if (overlayOn && (options.numberOfGrids > 1)) { + // Cycle through the available grids + overlay.removeClass(options.classPrefix + classNumber); + classNumber++; + if (classNumber > options.numberOfGrids) classNumber = 1; + overlay.addClass(options.classPrefix + classNumber); + if (/webkit/.test( navigator.userAgent.toLowerCase() )) { + forceRepaint(); + } + saveState(); + } + break; + } + } + + function keyupHandler(e) { + var m = getModifier(e); + if (!m) return true; + var k = getKey(e); + if (!k) return true; + if ((k == options.showGridKey) && !sticky) { + overlay.hide(); + overlayOn = false; + } + } + +} + + +/** + * Cookie functions + * + * By Peter-Paul Koch: + * http://www.quirksmode.org/js/cookies.html + */ +function createCookie(name,value,days) { + if (days) { + var date = new Date(); + date.setTime(date.getTime()+(days*24*60*60*1000)); + var expires = "; expires="+date.toGMTString(); + } + else var expires = ""; + document.cookie = name+"="+value+expires+"; path=/"; +} + +function readCookie(name) { + var nameEQ = name + "="; + var ca = document.cookie.split(';'); + for(var i=0;i < ca.length;i++) { + var c = ca[i]; + while (c.charAt(0)==' ') c = c.substring(1,c.length); + if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); + } + return null; +} + +function eraseCookie(name) { + createCookie(name,"",-1); +} + + +/** + * Forces a repaint (because WebKit has issues) + * http://www.sitepoint.com/forums/showthread.php?p=4538763 + * http://www.phpied.com/the-new-game-show-will-it-reflow/ + */ +function forceRepaint() { + var ss = document.styleSheets[0]; + try { + ss.addRule('.xxxxxx', 'position: relative'); + ss.removeRule(ss.rules.length - 1); + } catch(e){} +} \ No newline at end of file diff --git a/index.htm b/index.htm new file mode 100644 index 0000000..546f60e --- /dev/null +++ b/index.htm @@ -0,0 +1,375 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> +<html lang="en"> + +<head> +<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> +<title>#grid</title> + +<style type="text/css"> + +/* Putting inline rules here so the document can be downloaded with style */ + +body{ +font-size: 1em; +line-height: 1.25; +font-family: Arial, sans-serif; +background: White; +color: DimGray; +margin: 0; +padding: 0 20px; +} +#content{ +font-size: 16px; +line-height: 20px; +position: relative; +} +#content{ +width: 620px; +margin: 0 auto; +} +#footer{ +border-top: 1px dotted DarkGray; +padding-top: 19px; +} +h1, h2{ +color: Black; +font-weight: normal; +} +h1{ +font-size: 36px; +line-height: 40px; +margin: 40px 0 20px; +padding-bottom: 19px; +border-bottom: 1px dotted DarkGray; +} +h1 em{ +font-style: normal; +color: DarkGray; +font-size: 16px; +line-height: 20px; +margin: 0 0 20px; +} +h2, h3{ +font-size: 16px; +font-weight: 700; +line-height: 20px; +margin: 0 0 20px; +} +h3{ +font-weight: 300; +} +a:link, +a:visited{ +color: Black; +text-decoration: none; +padding: 0 2px; +background-color: WhiteSmoke; +border-bottom: 1px solid Gold; +} +a:focus{ +outline: none; +} +a:focus, +a:hover, +a:active{ +background-color: Khaki; +border-bottom: 1px solid GoldenRod; +} +p, ul{ +padding: 0; +margin: 0 0 20px; +} +dl, ol{ +padding: 0; +margin: 0; +} +ul{ +list-style: circle; +} +ol li{ +margin-bottom: 20px; +} +dd{ +margin: 0 0 20px 0; +} +del{ +text-decoration: line-through; +opacity: 0.75; +} +ins{ +text-decoration: none; +} +code{ +font-size: 14px; +line-height: 1; +} +textarea{ +font-family: 'Courier New', monospace; +font-size: 14px; +line-height: 20px; +display: block; +width: 600px; +margin: 0 0 20px; +padding: 0 0 0 15px; +border: 0; +color: Black; +background: Gainsboro; +border-left: 5px solid DarkGray; +} +#javascript-code{ +height: 180px; +} +#css-code{ +height: 1300px; +} +.summary em{ +font-style: normal; +position: absolute; +color: DarkGray; +right: 0; +top: 18px; +width: 140px; +} +.summary em span{ +position: absolute; +left: -9999px; +} +#download{ +line-height: 60px; +padding: 0 40px 0 15px; +border-left: 5px solid DarkGray; +background: Gainsboro; +color: DimGray; +} +span.key{ +color: Black; +text-transform: uppercase; +} +</style> + +<!-- Set styles --> +<style type="text/css"> + +/** + * Grid + */ +#grid{ + + /* Vertical grid lines */ + background: url(bg-grid-980.gif) repeat-y 0 0; + + /* Dimensions - same width as your grid with gutters */ + width: 980px; + + /* Grid (left-aligned) + position: absolute; + top: 0; + left: 0; + */ + + /* Grid (centered) */ + position: absolute; + top: 0; + left: 50%; + margin-left: -490px; + +} + +/** + * Classes for multiple grids + * + * When using more than one grid, remember to set the numberOfGrids + * option in the hashgrid.js file. + */ +#grid.grid-1{ + + /* Vertical grid lines for grid 1 */ + background: url(bg-grid-980.gif) repeat-y 0 0; + +} +#grid.grid-2{ + + /* Vertical grid lines for grid 2 */ + background: url(bg-grid-660.gif) repeat-y 160px 0; + + /* Adjustments */ + padding: 0 160px; + width: 660px; + +} + +/** + * Horizontal grid lines, defined by your base line height + * + * Remember, the CSS properties that define the box model: + * visible height = height + borders + margins + padding + */ +#grid div.horiz{ + + /* 20px line height */ + height: 19px; + border-bottom: 1px dotted #aaa; + margin: 0; + padding: 0; + +} + +</style> + +</head> + +<body> + +<div id="content" role="main"> + +<h1>#grid <em>v4</em></h1> + +<p class="summary"><em>Mon, 29 Mar 2010<span>:</span></em> This is a little tool we created for our <a href="http://analog.coop/">Analog&#160;holding&#160;page</a>. It inserts a <a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a> in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit <span class="key">G</span> on your keyboard.</p> + +<h2>Download</h2> +<p id="download"><a href="http://github.com/dotjay/hashgrid/downloads">Download #grid</a> from <a href="http://github.com/dotjay/hashgrid">GitHub</a></p> + +<h2 id="features">Features</h2> +<ul> +<li>Adaptable for all layout widths and alignments</li> +<li>Adaptable for any vertical rhythm value</li> +<li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li> +<li>Uses a single JavaScript file, a little CSS, and an image (for the vertical lines)</li> +</ul> +<p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p> + +<h2 id="installation">Installation</h2> +<ol> +<li><h3>Copy the <a href="http://github.com/dotjay/hashgrid/blob/master/hashgrid.js">hashgrid.js</a> script to your project</h3></li> +<li><h3>Add the script to your page(s) just inside the <code>&#60;/body&#62;</code> tag</h3> +<textarea id="javascript-code" cols="68" rows="8" readonly="readonly"> + +&#60;!-- Grab latest version of jQuery --&#62; +&#60;script type="text/javascript" + src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"&#62; +&#60;/script&#62; + +&#60;!-- Include the hashgrid script --&#62; +&#60;script type="text/javascript" src="hashgrid.js"&#62;&#60;/script&#62;</textarea></li> +<li><h3>Add the CSS to your page(s)</h3> +<textarea id="css-code" cols="68" rows="64" readonly="readonly"> + +/** + * Grid + */ +#grid{ + + /* Vertical grid lines */ + background: url(bg-grid-980.gif) repeat-y 0 0; + + /* Dimensions - same width as your grid with gutters */ + width: 980px; + + /* Grid (left-aligned) + position: absolute; + top: 0; + left: 0; + */ + + /* Grid (centered) */ + position: absolute; + top: 0; + left: 50%; + margin-left: -490px; + +} + +/** + * Classes for multiple grids + * + * When using more than one grid, remember to set the numberOfGrids + * option in the hashgrid.js file. + */ +#grid.grid-1{ + + /* Vertical grid lines for grid 1 */ + background: url(bg-grid-980.gif) repeat-y 0 0; + +} +#grid.grid-2{ + + /* Vertical grid lines for grid 2 */ + background: url(bg-grid-660.gif) repeat-y 160px 0; + + /* Adjustments */ + padding: 0 160px; + width: 660px; + +} + +/** + * Horizontal grid lines, defined by your base line height + * + * Remember, the CSS properties that define the box model: + * visible height = height + borders + margins + padding + */ +#grid div.horiz{ + + /* 20px line height */ + height: 19px; + border-bottom: 1px dotted #aaa; + margin: 0; + padding: 0; + +} +</textarea></li> +<li><h3>Modify #grid to suit your needs</h3> +<p>The CSS and JavaScript is annotated to help you. We&#8217;ve included a <a href="bg-grid-980.gif">980px-wide background image</a> to provide the vertical grid lines (a 940-pixel-wide content area with 20px gutters). If you&#8217;re working to a <a href="http://www.markboulton.co.uk/journal/comments/five-simple-steps-to-designing-grid-systems-part-1">different grid</a>, you will need to create a new image for your guides. Don&#8217;t forget to make the background transparent!</p></li> +</ol> + +<h2 id="usage">Usage</h2> +<p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p> +<dl> +<dt><span class="key">G</span></dt> +<dd>Show the grid until you release.</dd> +<dt><span class="key">G</span> + <span class="key">H</span></dt> +<dd>Show and hold the grid (<span class="key">G</span> will remove it again).</dd> +<dt><span class="key">G</span> + <span class="key">F</span></dt> +<dd>Toggle the grid to the foreground and back. Pressing <span class="key">F</span> while the grid is held also works.</dd> +<dt><span class="key">G</span> + <span class="key">J</span></dt> +<dd>Jump to the next grid. Pressing <span class="key">J</span> while the grid is held also works.</dd> +</dl> +<p><em>N.B. A cookie conveniently remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em></p> + +<h2 id="release-notes">Release Notes</h2> +<dl> +<dt>v4&#8201;&#8212;&#8201;29 Mar 2010</dt> +<dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd> +<dt>v3&#8201;&#8212;&#8201;22 Feb 2010</dt> +<dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd> +<dt>v2&#8201;&#8212;&#8201;2 Feb 2010</dt> +<dd>Keys are now more easily configured (see top of hashgrid.js). Renamed the GridOverlay object to hashgrid. Fixed crash when using with disabled CSS.</dd> +<dt>v1&#8201;&#8212;&#8201;21 Dec 2009</dt> +<dd>First release.</dd> +</dl> + +<h2 id="known-issues">Known Issues</h2> +<ul> +<li><del>IE 8: Fully functional, but the default <span class="key">ALT</span> + <span class="key">G</span> + <span class="key">ENTER</span> shortcut puts IE into full screen mode. Hit <span class="key">ALT</span> + <span class="key">ENTER</span> to toggle full screen mode off again.</del><ins datetime="2010-02-22"> The default keyboard shortcuts have been changed.</ins></li> +<li>IE 6: The grid is always in the foreground.</li> +<li>Opera 9/10: Using <span class="key">CTRL</span> or <span class="key">ALT</span> as a modifier key will not work due to different key handling by the browser.</li> +</ul> + +<h2 id="license">License</h2> +<p>Released under a <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike License</a>, which essentially means that you&#8217;re free to copy it and adapt it. <a href="http://analog.coop/#talk-to-us">Contact us at Analog</a> if you need a different license.</p> + +<div id="footer" role="contentinfo"> +<p>#grid is an <a href="http://analog.coop/">Analog</a> gig. It was conceived by <a href="http://jontangerine.com/">Jon Tan</a>, and built by <a href="http://accessibility.co.uk/">Jon Gibbins</a>, in cahoots with our <a href="http://analog.coop#is">fine friends</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p> +</div> + +</div> + +<!-- Grab latest version of jQuery --> +<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> + +<!-- Include the hashgrid script --> +<script type="text/javascript" src="hashgrid.js"></script> + +</body> + +</html>
dotjay/hashgrid
f6cfb9d7bfbe37aa5616183d6dcd836bb9d9e276
Documenting version 4.
diff --git a/README.md b/README.md new file mode 100644 index 0000000..820917a --- /dev/null +++ b/README.md @@ -0,0 +1,14 @@ +#grid +===== + +A little tool that inserts a layout grid in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. + +Features +-------- + + * Adaptable for all layout widths and alignments + * Adaptable for any vertical rhythm value + * Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids + * Uses a single JavaScript file, a little CSS, and an image (for the vertical lines) + +Notes on installation and usage can be found in the included index.htm file. diff --git a/bg-grid-660.gif b/bg-grid-660.gif new file mode 100755 index 0000000..0418c18 Binary files /dev/null and b/bg-grid-660.gif differ diff --git a/bg-grid-980.gif b/bg-grid-980.gif new file mode 100644 index 0000000..a4a8c01 Binary files /dev/null and b/bg-grid-980.gif differ diff --git a/hashgrid.js b/hashgrid.js new file mode 100644 index 0000000..7f78c8a --- /dev/null +++ b/hashgrid.js @@ -0,0 +1,290 @@ +/** + * hashgrid (jQuery version) + * http://github.com/dotjay/hashgrid + * Version 4, 29 Mar 2010 + * By Jon Gibbins, accessibility.co.uk + * + * // Using a basic #grid setup + * var grid = new hashgrid(); + * + * // Using #grid with a custom id (e.g. #mygrid) + * var grid = new hashgrid("mygrid"); + * + * // Using #grid with additional options + * var grid = new hashgrid({ + * id: 'mygrid', // id for the grid container + * modifierKey: 'alt', // optional 'ctrl', 'alt' or 'shift' + * showGridKey: 's', // key to show the grid + * holdGridKey: 'enter', // key to hold the grid in place + * foregroundKey: 'f', // key to toggle foreground/background + * jumpGridsKey: 'd', // key to cycle through the grid classes + * numberOfGrids: 2, // number of grid classes used + * classPrefix: 'class', // prefix for the grid classes + * cookiePrefix: 'mygrid' // prefix for the cookie name + * }); + */ + + +/** + * You can call hashgrid from your own code, but it's loaded here by + * default for convenience. + */ +$(document).ready(function() { + + var grid = new hashgrid({ + numberOfGrids: 2 + }); + +}); + + +/** + * hashgrid overlay + */ +var hashgrid = function(set) { + + var options = { + id: 'grid', // id for the grid container + modifierKey: null, // optional 'ctrl', 'alt' or 'shift' + showGridKey: 'g', // key to show the grid + holdGridKey: 'h', // key to hold the grid in place + foregroundKey: 'f', // key to toggle foreground/background + jumpGridsKey: 'j', // key to cycle through the grid classes + numberOfGrids: 1, // number of grid classes used + classPrefix: 'grid-', // prefix for the grid classes + cookiePrefix: 'hashgrid'// prefix for the cookie name + }; + var overlayOn = false, + sticky = false, + overlayZState = 'B', + overlayZBackground = -1, + overlayZForeground = 9999, + classNumber = 1; + + // Apply options + if (typeof set == 'object') { + var k; + for (k in set) options[k] = set[k]; + } + else if (typeof set == 'string') { + options.id = set; + } + + // Remove any conflicting overlay + if ($('#' + options.id).length > 0) { + $('#' + options.id).remove(); + } + + // Create overlay, hidden before adding to DOM + var overlayEl = $('<div></div>'); + overlayEl + .attr('id', options.id) + .css('display', 'none'); + $("body").prepend(overlayEl); + var overlay = $('#' + options.id); + + // Unless a custom z-index is set, ensure the overlay will be behind everything + if (overlay.css('z-index') == 'auto') overlay.css('z-index', overlayZBackground); + + // Override the default overlay height with the actual page height + var pageHeight = parseFloat($(document).height()); + overlay.height(pageHeight); + + // Add the first grid line so that we can measure it + overlay.append('<div class="horiz first-line">'); + + // Calculate the number of grid lines needed + var overlayGridLines = overlay.children('.horiz'), + overlayGridLineHeight = parseFloat(overlayGridLines.css('height')) + parseFloat(overlayGridLines.css('border-bottom-width')); + + // Break on zero line height + if (overlayGridLineHeight <= 0) return true; + + // Add the remaining grid lines + var i, numGridLines = Math.floor(pageHeight / overlayGridLineHeight); + for (i = numGridLines - 1; i >= 1; i--) { + overlay.append('<div class="horiz"></div>'); + } + + // Check for saved state + var overlayCookie = readCookie(options.cookiePrefix + options.id); + if (typeof overlayCookie == 'string') { + var state = overlayCookie.split(','); + state[2] = Number(state[2]); + if ((typeof state[2] == 'number') && !isNaN(state[2])) { + classNumber = state[2].toFixed(0); + overlay.addClass(options.classPrefix + classNumber); + } + if (state[1] == 'F') { + overlayZState = 'F'; + overlay.css('z-index', overlayZForeground); + } + if (state[0] == '1') { + overlayOn = true; + sticky = true; + overlay.show(); + } + } + else { + overlay.addClass(options.classPrefix + classNumber) + } + + // Keyboard controls + $(document).bind('keydown', keydownHandler); + $(document).bind('keyup', keyupHandler); + + /** + * Helpers + */ + + function getModifier(e) { + if (options.modifierKey == null) return true; // Bypass by default + var m = true; + switch(options.modifierKey) { + case 'ctrl': + m = (e.ctrlKey ? e.ctrlKey : false); + break; + + case 'alt': + m = (e.altKey ? e.altKey : false); + break; + + case 'shift': + m = (e.shiftKey ? e.shiftKey : false); + break; + } + return m; + } + + function getKey(e) { + var k = false, c = (e.keyCode ? e.keyCode : e.which); + // Handle keywords + if (c == 13) k = 'enter'; + // Handle letters + else k = String.fromCharCode(c).toLowerCase(); + return k; + } + + function saveState() { + createCookie(options.cookiePrefix + options.id, (sticky ? '1' : '0') + ',' + overlayZState + ',' + classNumber, 1); + } + + /** + * Event handlers + */ + + function keydownHandler(e) { + var source = e.target.tagName.toLowerCase(); + if ((source == 'input') || (source == 'textarea') || (source == 'select')) return true; + var m = getModifier(e); + if (!m) return true; + var k = getKey(e); + if (!k) return true; + switch(k) { + case options.showGridKey: + if (!overlayOn) { + overlay.show(); + overlayOn = true; + } + else if (sticky) { + overlay.hide(); + overlayOn = false; + sticky = false; + saveState(); + } + break; + case options.holdGridKey: + if (overlayOn && !sticky) { + // Turn sticky overlay on + sticky = true; + saveState(); + } + break; + case options.foregroundKey: + if (overlayOn) { + // Toggle sticky overlay z-index + if (overlay.css('z-index') == overlayZForeground) { + overlay.css('z-index', overlayZBackground); + overlayZState = 'B'; + } + else { + overlay.css('z-index', overlayZForeground); + overlayZState = 'F'; + } + saveState(); + } + break; + case options.jumpGridsKey: + if (overlayOn && (options.numberOfGrids > 1)) { + // Cycle through the available grids + overlay.removeClass(options.classPrefix + classNumber); + classNumber++; + if (classNumber > options.numberOfGrids) classNumber = 1; + overlay.addClass(options.classPrefix + classNumber); + if (/webkit/.test( navigator.userAgent.toLowerCase() )) { + forceRepaint(); + } + saveState(); + } + break; + } + } + + function keyupHandler(e) { + var m = getModifier(e); + if (!m) return true; + var k = getKey(e); + if (!k) return true; + if ((k == options.showGridKey) && !sticky) { + overlay.hide(); + overlayOn = false; + } + } + +} + + +/** + * Cookie functions + * + * By Peter-Paul Koch: + * http://www.quirksmode.org/js/cookies.html + */ +function createCookie(name,value,days) { + if (days) { + var date = new Date(); + date.setTime(date.getTime()+(days*24*60*60*1000)); + var expires = "; expires="+date.toGMTString(); + } + else var expires = ""; + document.cookie = name+"="+value+expires+"; path=/"; +} + +function readCookie(name) { + var nameEQ = name + "="; + var ca = document.cookie.split(';'); + for(var i=0;i < ca.length;i++) { + var c = ca[i]; + while (c.charAt(0)==' ') c = c.substring(1,c.length); + if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); + } + return null; +} + +function eraseCookie(name) { + createCookie(name,"",-1); +} + + +/** + * Forces a repaint (because WebKit has issues) + * http://www.sitepoint.com/forums/showthread.php?p=4538763 + * http://www.phpied.com/the-new-game-show-will-it-reflow/ + */ +function forceRepaint() { + var ss = document.styleSheets[0]; + try { + ss.addRule('.xxxxxx', 'position: relative'); + ss.removeRule(ss.rules.length - 1); + } catch(e){} +} \ No newline at end of file diff --git a/index.htm b/index.htm new file mode 100644 index 0000000..546f60e --- /dev/null +++ b/index.htm @@ -0,0 +1,375 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> +<html lang="en"> + +<head> +<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> +<title>#grid</title> + +<style type="text/css"> + +/* Putting inline rules here so the document can be downloaded with style */ + +body{ +font-size: 1em; +line-height: 1.25; +font-family: Arial, sans-serif; +background: White; +color: DimGray; +margin: 0; +padding: 0 20px; +} +#content{ +font-size: 16px; +line-height: 20px; +position: relative; +} +#content{ +width: 620px; +margin: 0 auto; +} +#footer{ +border-top: 1px dotted DarkGray; +padding-top: 19px; +} +h1, h2{ +color: Black; +font-weight: normal; +} +h1{ +font-size: 36px; +line-height: 40px; +margin: 40px 0 20px; +padding-bottom: 19px; +border-bottom: 1px dotted DarkGray; +} +h1 em{ +font-style: normal; +color: DarkGray; +font-size: 16px; +line-height: 20px; +margin: 0 0 20px; +} +h2, h3{ +font-size: 16px; +font-weight: 700; +line-height: 20px; +margin: 0 0 20px; +} +h3{ +font-weight: 300; +} +a:link, +a:visited{ +color: Black; +text-decoration: none; +padding: 0 2px; +background-color: WhiteSmoke; +border-bottom: 1px solid Gold; +} +a:focus{ +outline: none; +} +a:focus, +a:hover, +a:active{ +background-color: Khaki; +border-bottom: 1px solid GoldenRod; +} +p, ul{ +padding: 0; +margin: 0 0 20px; +} +dl, ol{ +padding: 0; +margin: 0; +} +ul{ +list-style: circle; +} +ol li{ +margin-bottom: 20px; +} +dd{ +margin: 0 0 20px 0; +} +del{ +text-decoration: line-through; +opacity: 0.75; +} +ins{ +text-decoration: none; +} +code{ +font-size: 14px; +line-height: 1; +} +textarea{ +font-family: 'Courier New', monospace; +font-size: 14px; +line-height: 20px; +display: block; +width: 600px; +margin: 0 0 20px; +padding: 0 0 0 15px; +border: 0; +color: Black; +background: Gainsboro; +border-left: 5px solid DarkGray; +} +#javascript-code{ +height: 180px; +} +#css-code{ +height: 1300px; +} +.summary em{ +font-style: normal; +position: absolute; +color: DarkGray; +right: 0; +top: 18px; +width: 140px; +} +.summary em span{ +position: absolute; +left: -9999px; +} +#download{ +line-height: 60px; +padding: 0 40px 0 15px; +border-left: 5px solid DarkGray; +background: Gainsboro; +color: DimGray; +} +span.key{ +color: Black; +text-transform: uppercase; +} +</style> + +<!-- Set styles --> +<style type="text/css"> + +/** + * Grid + */ +#grid{ + + /* Vertical grid lines */ + background: url(bg-grid-980.gif) repeat-y 0 0; + + /* Dimensions - same width as your grid with gutters */ + width: 980px; + + /* Grid (left-aligned) + position: absolute; + top: 0; + left: 0; + */ + + /* Grid (centered) */ + position: absolute; + top: 0; + left: 50%; + margin-left: -490px; + +} + +/** + * Classes for multiple grids + * + * When using more than one grid, remember to set the numberOfGrids + * option in the hashgrid.js file. + */ +#grid.grid-1{ + + /* Vertical grid lines for grid 1 */ + background: url(bg-grid-980.gif) repeat-y 0 0; + +} +#grid.grid-2{ + + /* Vertical grid lines for grid 2 */ + background: url(bg-grid-660.gif) repeat-y 160px 0; + + /* Adjustments */ + padding: 0 160px; + width: 660px; + +} + +/** + * Horizontal grid lines, defined by your base line height + * + * Remember, the CSS properties that define the box model: + * visible height = height + borders + margins + padding + */ +#grid div.horiz{ + + /* 20px line height */ + height: 19px; + border-bottom: 1px dotted #aaa; + margin: 0; + padding: 0; + +} + +</style> + +</head> + +<body> + +<div id="content" role="main"> + +<h1>#grid <em>v4</em></h1> + +<p class="summary"><em>Mon, 29 Mar 2010<span>:</span></em> This is a little tool we created for our <a href="http://analog.coop/">Analog&#160;holding&#160;page</a>. It inserts a <a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a> in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit <span class="key">G</span> on your keyboard.</p> + +<h2>Download</h2> +<p id="download"><a href="http://github.com/dotjay/hashgrid/downloads">Download #grid</a> from <a href="http://github.com/dotjay/hashgrid">GitHub</a></p> + +<h2 id="features">Features</h2> +<ul> +<li>Adaptable for all layout widths and alignments</li> +<li>Adaptable for any vertical rhythm value</li> +<li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li> +<li>Uses a single JavaScript file, a little CSS, and an image (for the vertical lines)</li> +</ul> +<p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p> + +<h2 id="installation">Installation</h2> +<ol> +<li><h3>Copy the <a href="http://github.com/dotjay/hashgrid/blob/master/hashgrid.js">hashgrid.js</a> script to your project</h3></li> +<li><h3>Add the script to your page(s) just inside the <code>&#60;/body&#62;</code> tag</h3> +<textarea id="javascript-code" cols="68" rows="8" readonly="readonly"> + +&#60;!-- Grab latest version of jQuery --&#62; +&#60;script type="text/javascript" + src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"&#62; +&#60;/script&#62; + +&#60;!-- Include the hashgrid script --&#62; +&#60;script type="text/javascript" src="hashgrid.js"&#62;&#60;/script&#62;</textarea></li> +<li><h3>Add the CSS to your page(s)</h3> +<textarea id="css-code" cols="68" rows="64" readonly="readonly"> + +/** + * Grid + */ +#grid{ + + /* Vertical grid lines */ + background: url(bg-grid-980.gif) repeat-y 0 0; + + /* Dimensions - same width as your grid with gutters */ + width: 980px; + + /* Grid (left-aligned) + position: absolute; + top: 0; + left: 0; + */ + + /* Grid (centered) */ + position: absolute; + top: 0; + left: 50%; + margin-left: -490px; + +} + +/** + * Classes for multiple grids + * + * When using more than one grid, remember to set the numberOfGrids + * option in the hashgrid.js file. + */ +#grid.grid-1{ + + /* Vertical grid lines for grid 1 */ + background: url(bg-grid-980.gif) repeat-y 0 0; + +} +#grid.grid-2{ + + /* Vertical grid lines for grid 2 */ + background: url(bg-grid-660.gif) repeat-y 160px 0; + + /* Adjustments */ + padding: 0 160px; + width: 660px; + +} + +/** + * Horizontal grid lines, defined by your base line height + * + * Remember, the CSS properties that define the box model: + * visible height = height + borders + margins + padding + */ +#grid div.horiz{ + + /* 20px line height */ + height: 19px; + border-bottom: 1px dotted #aaa; + margin: 0; + padding: 0; + +} +</textarea></li> +<li><h3>Modify #grid to suit your needs</h3> +<p>The CSS and JavaScript is annotated to help you. We&#8217;ve included a <a href="bg-grid-980.gif">980px-wide background image</a> to provide the vertical grid lines (a 940-pixel-wide content area with 20px gutters). If you&#8217;re working to a <a href="http://www.markboulton.co.uk/journal/comments/five-simple-steps-to-designing-grid-systems-part-1">different grid</a>, you will need to create a new image for your guides. Don&#8217;t forget to make the background transparent!</p></li> +</ol> + +<h2 id="usage">Usage</h2> +<p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p> +<dl> +<dt><span class="key">G</span></dt> +<dd>Show the grid until you release.</dd> +<dt><span class="key">G</span> + <span class="key">H</span></dt> +<dd>Show and hold the grid (<span class="key">G</span> will remove it again).</dd> +<dt><span class="key">G</span> + <span class="key">F</span></dt> +<dd>Toggle the grid to the foreground and back. Pressing <span class="key">F</span> while the grid is held also works.</dd> +<dt><span class="key">G</span> + <span class="key">J</span></dt> +<dd>Jump to the next grid. Pressing <span class="key">J</span> while the grid is held also works.</dd> +</dl> +<p><em>N.B. A cookie conveniently remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em></p> + +<h2 id="release-notes">Release Notes</h2> +<dl> +<dt>v4&#8201;&#8212;&#8201;29 Mar 2010</dt> +<dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd> +<dt>v3&#8201;&#8212;&#8201;22 Feb 2010</dt> +<dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd> +<dt>v2&#8201;&#8212;&#8201;2 Feb 2010</dt> +<dd>Keys are now more easily configured (see top of hashgrid.js). Renamed the GridOverlay object to hashgrid. Fixed crash when using with disabled CSS.</dd> +<dt>v1&#8201;&#8212;&#8201;21 Dec 2009</dt> +<dd>First release.</dd> +</dl> + +<h2 id="known-issues">Known Issues</h2> +<ul> +<li><del>IE 8: Fully functional, but the default <span class="key">ALT</span> + <span class="key">G</span> + <span class="key">ENTER</span> shortcut puts IE into full screen mode. Hit <span class="key">ALT</span> + <span class="key">ENTER</span> to toggle full screen mode off again.</del><ins datetime="2010-02-22"> The default keyboard shortcuts have been changed.</ins></li> +<li>IE 6: The grid is always in the foreground.</li> +<li>Opera 9/10: Using <span class="key">CTRL</span> or <span class="key">ALT</span> as a modifier key will not work due to different key handling by the browser.</li> +</ul> + +<h2 id="license">License</h2> +<p>Released under a <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike License</a>, which essentially means that you&#8217;re free to copy it and adapt it. <a href="http://analog.coop/#talk-to-us">Contact us at Analog</a> if you need a different license.</p> + +<div id="footer" role="contentinfo"> +<p>#grid is an <a href="http://analog.coop/">Analog</a> gig. It was conceived by <a href="http://jontangerine.com/">Jon Tan</a>, and built by <a href="http://accessibility.co.uk/">Jon Gibbins</a>, in cahoots with our <a href="http://analog.coop#is">fine friends</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p> +</div> + +</div> + +<!-- Grab latest version of jQuery --> +<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> + +<!-- Include the hashgrid script --> +<script type="text/javascript" src="hashgrid.js"></script> + +</body> + +</html>
dmaclay/python-smpp
4b37d211ea38f52ae282a469e377baabbcd17199
comment typo
diff --git a/tests.py b/tests.py index ce71d8c..913af68 100644 --- a/tests.py +++ b/tests.py @@ -1,339 +1,339 @@ # -*- coding: utf-8 -*- import unittest, collections from datetime import datetime, timedelta from smpp.esme import * from smpp.clickatell import * from smpp import pdu import credentials_test try:import credentials_priv except:pass from test.pdu import pdu_objects from test import pdu_asserts from test.pdu_hex import pdu_hex_strings from test import pdu_hex_asserts def unpack_hex(pdu_hex): """Unpack PDU hex string and return it as a dictionary""" return unpack_pdu(binascii.a2b_hex(hexclean(pdu_hex))) def hexclean(dirtyhex): """Remove whitespace, comments & newlines from hex string""" return re.sub(r'\s','',re.sub(r'#.*\n','\n',dirtyhex)) def prettydump(pdu_obj): """Unpack PDU dictionary and dump it as a JSON formatted string""" return json.dumps(pdu_obj, indent=4, sort_keys=True) def hex_to_named(dictionary): """ Recursive function to convert values in test dictionaries to their named counterparts that unpack_pdu returns """ clone = dictionary.copy() for key, value in clone.items(): if isinstance(value, collections.Mapping): clone[key] = hex_to_named(value) else: lookup_table = pdu.maps.get('%s_by_hex' % key) if lookup_table: # overwrite with mapped value or keep using # default if the dictionary key doesn't exist clone[key] = lookup_table.get("%.2d" % value, value) return clone def create_pdu_asserts(): pdu_index = 0 for pdu in pdu_objects: pdu_index += 1 pstr = "\n########################################\n" pstr += "pdu_json_" pstr += ('%010d' % pdu_index) pstr += " = '''" pstr += prettydump(unpack_pdu(pack_pdu(pdu))) pstr += "'''" print pstr def create_pdu_hex_asserts(): pdu_index = 0 for pdu_hex in pdu_hex_strings: pdu_index += 1 pstr = "\n########################################\n" pstr += "pdu_json_" pstr += ('%010d' % pdu_index) pstr += " = '''" pstr += prettydump(unpack_hex(pdu_hex)) pstr += "'''" print pstr ## :w|!python % > test/pdu_asserts.py #create_pdu_asserts() #quit() ## :w|!python % > test/pdu_hex_asserts.py #create_pdu_hex_asserts() #quit() class PduTestCase(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def assertDictEquals(self, dictionary1, dictionary2, depth=[]): """ Recursive dictionary comparison, will fail if any keys and values in the two dictionaries don't match. Displays the key chain / depth and which parts of the two dictionaries didn't match. """ d1_keys = dictionary1.keys() d1_keys.sort() d2_keys = dictionary2.keys() d2_keys.sort() self.failUnlessEqual(d1_keys, d2_keys, "Dictionary keys do not match, %s vs %s" % ( d1_keys, d2_keys)) for key, value in dictionary1.items(): if isinstance(value, collections.Mapping): # go recursive depth.append(key) self.assertDictEquals(value, dictionary2[key], depth) else: self.failUnlessEqual(value, dictionary2[key], "Dictionary values do not match for key '%s' " \ "(%s vs %s) at depth: %s.\nDictionary 1: %s\n" \ "Dictionary 2: %s\n" % ( key, value, dictionary2[key], ".".join(depth), prettydump(dictionary1), prettydump(dictionary2))) def test_pack_unpack_pdu_objects(self): print '' """ Take a dictionary, pack and unpack it and dump it as JSON correctly """ pdu_index = 0 for pdu in pdu_objects: pdu_index += 1 padded_index = '%010d' % pdu_index print '...', padded_index self.assertEquals( re.sub('\n *','', prettydump(unpack_pdu(pack_pdu(pdu)))), re.sub('\n *','', eval('pdu_asserts.pdu_json_'+padded_index))) def test_pack_unpack_pdu_hex_strings(self): print '' """ Read the hex data, clean it, and unpack it to JSON correctly """ pdu_index = 0 for pdu_hex in pdu_hex_strings: pdu_index += 1 padded_index = '%010d' % pdu_index print '...', padded_index self.assertEquals( re.sub('\n *','', prettydump(unpack_hex(pdu_hex))), re.sub('\n *','', eval('pdu_hex_asserts.pdu_json_'+padded_index))) def test_pack_unpack_performance(self): print '' """ - Pack & unpack 2000 submit_sm PDUs in under 1 second + Pack & unpack 500 submit_sm PDUs in under 1 second """ submit_sm = { 'header': { 'command_length': 0, 'command_id': 'submit_sm', 'command_status': 'ESME_ROK', 'sequence_number': 0, }, 'body': { 'mandatory_parameters': { 'service_type':'', 'source_addr_ton':1, 'source_addr_npi':1, 'source_addr':'', 'dest_addr_ton':1, 'dest_addr_npi':1, 'destination_addr':'', 'esm_class':0, 'protocol_id':0, 'priority_flag':0, 'schedule_delivery_time':'', 'validity_period':'', 'registered_delivery':0, 'replace_if_present_flag':0, 'data_coding':0, 'sm_default_msg_id':0, 'sm_length':1, 'short_message':'', }, }, } start = datetime.now() for x in range(500): x += 1 submit_sm['header']['sequence_number'] = x sm = 'testing: x = '+str(x)+'' submit_sm['body']['mandatory_parameters']['short_message'] = sm u = unpack_pdu(pack_pdu(submit_sm)) delta = datetime.now() - start - print '... 1000 pack & unpacks in:', delta + print '... 500 pack & unpacks in:', delta self.assertTrue(delta < timedelta(seconds=1)) def test_pack_unpack_of_unicode(self): """ SMPP module should be able to pack & unpack unicode characters without a problem """ submit_sm = { 'header': { 'command_length': 67, 'command_id': 'submit_sm', 'command_status': 'ESME_ROK', 'sequence_number': 0, }, 'body': { 'mandatory_parameters': { 'service_type':'', 'source_addr_ton':'international', 'source_addr_npi':'unknown', 'source_addr':'', 'dest_addr_ton':'international', 'dest_addr_npi':'unknown', 'destination_addr':'', 'esm_class':0, 'protocol_id':0, 'priority_flag':0, 'schedule_delivery_time':'', 'validity_period':'', 'registered_delivery':0, 'replace_if_present_flag':0, 'data_coding':0, 'sm_default_msg_id':0, 'sm_length':34, 'short_message':u'Vumi says: أبن الشرموطة'.encode('utf-8'), }, }, } self.assertDictEquals( hex_to_named(submit_sm), unpack_pdu(pack_pdu(submit_sm)) ) def test_pack_unpack_of_ascii_and_unicode_8_16_32(self): """ SMPP module should be able to pack & unpack unicode characters without a problem """ submit_sm = { 'header': { 'command_length': 65, 'command_id': 'submit_sm', 'command_status': 'ESME_ROK', 'sequence_number': 0, }, 'body': { 'mandatory_parameters': { 'service_type':'', 'source_addr_ton':'international', 'source_addr_npi':'unknown', 'source_addr':'', 'dest_addr_ton':'international', 'dest_addr_npi':'unknown', 'destination_addr':'', 'esm_class':0, 'protocol_id':0, 'priority_flag':0, 'schedule_delivery_time':'', 'validity_period':'', 'registered_delivery':0, 'replace_if_present_flag':0, 'data_coding':0, 'sm_default_msg_id':0, 'sm_length':32, 'short_message':u'a \xf0\x20\u0373\u0020\u0433\u0020\u0533\u0020\u05f3\u0020\u0633\u0020\u13a3\u0020\u16a3 \U0001f090'.encode('utf-8'), }, }, } self.assertDictEquals( hex_to_named(submit_sm), unpack_pdu(pack_pdu(submit_sm)) ) class PduBuilderTestCase(unittest.TestCase): def test_true(self): print '' self.assertTrue(True) if __name__ == '__main__': print '\n##########################################################\n' #deliv_sm_resp = DeliverSMResp(23) #print deliv_sm_resp.get_obj() #print deliv_sm_resp.get_hex() #enq_lnk = EnquireLink(7) #print enq_lnk.get_obj() #print enq_lnk.get_hex() #sub_sm = SubmitSM(5, short_message='testing testing') #print sub_sm.get_obj() #print sub_sm.get_hex() #sub_sm.add_message_payload('01020304') #print sub_sm.get_obj() #print sub_sm.get_hex() #print unpack_pdu(sub_sm.get_bin()) print '\n##########################################################\n' esme = ESME() esme.loadDefaults(clickatell_defaults) esme.loadDefaults(credentials_test.logica) print esme.defaults esme.bind_transmitter() print esme.state start = datetime.now() for x in range(1): esme.submit_sm( short_message = 'gobbledygook', destination_addr = '555', ) print esme.state for x in range(1): esme.submit_multi( short_message = 'gobbledygook', dest_address = ['444','333'], ) print esme.state for x in range(1): esme.submit_multi( short_message = 'gobbledygook', dest_address = [ {'dest_flag':1, 'destination_addr':'111'}, {'dest_flag':2, 'dl_name':'list22222'}, ], ) print esme.state delta = datetime.now() - start esme.disconnect() print esme.state print 'excluding binding ... time to send messages =', delta #if __name__ == '__main__': #unittest.main()
dmaclay/python-smpp
5b616942b82bf9155b6fb911b175c5fcb12b792f
optional command_status on bind_resp's
diff --git a/smpp/pdu_builder.py b/smpp/pdu_builder.py index e143905..6f32a51 100644 --- a/smpp/pdu_builder.py +++ b/smpp/pdu_builder.py @@ -1,358 +1,362 @@ from pdu import * class PDU(object): def __init__(self, command_id, command_status, sequence_number, **kwargs): super(PDU, self).__init__() self.obj = {} self.obj['header'] = {} self.obj['header']['command_length'] = 0 self.obj['header']['command_id'] = command_id self.obj['header']['command_status'] = command_status self.obj['header']['sequence_number'] = sequence_number def __add_optional_parameter(self, tag, value): if self.obj.get('body') == None: self.obj['body'] = {} if self.obj['body'].get('optional_parameters') == None: self.obj['body']['optional_parameters'] = [] self.obj['body']['optional_parameters'].append({ 'tag':tag, 'length':0, 'value':value, }) def set_sar_msg_ref_num(self, value): self.__add_optional_parameter('sar_msg_ref_num', value) def set_sar_segment_seqnum(self, value): self.__add_optional_parameter('sar_segment_seqnum', value) def set_sar_total_segments(self, value): self.__add_optional_parameter('sar_total_segments', value) def get_obj(self): return self.obj def get_hex(self): return encode_pdu(self.obj) def get_bin(self): return pack_pdu(self.obj) class Bind(PDU): def __init__(self, command_id, sequence_number, system_id = '', password = '', system_type = '', interface_version = '34', addr_ton = 0, addr_npi = 0, address_range = '', **kwargs): super(Bind, self).__init__( command_id, 'ESME_ROK', sequence_number, ) self.obj['body'] = {} self.obj['body']['mandatory_parameters'] = {} self.obj['body']['mandatory_parameters']['system_id'] = system_id self.obj['body']['mandatory_parameters']['password'] = password self.obj['body']['mandatory_parameters']['system_type'] = system_type self.obj['body']['mandatory_parameters']['interface_version'] = interface_version self.obj['body']['mandatory_parameters']['addr_ton'] = addr_ton self.obj['body']['mandatory_parameters']['addr_npi'] = addr_npi self.obj['body']['mandatory_parameters']['address_range'] = address_range class BindTransmitter(Bind): def __init__(self, sequence_number, **kwargs): super(BindTransmitter, self).__init__('bind_transmitter', sequence_number, **kwargs) class BindReceiver(Bind): def __init__(self, sequence_number, **kwargs): super(BindReceiver, self).__init__('bind_receiver', sequence_number, **kwargs) class BindTransceiver(Bind): def __init__(self, sequence_number, **kwargs): super(BindTransceiver, self).__init__('bind_transceiver', sequence_number, **kwargs) class BindResp(PDU): def __init__(self, command_id, + command_status, sequence_number, system_id = '', **kwargs): super(BindResp, self).__init__( command_id, - 'ESME_ROK', + command_status, sequence_number, ) self.obj['body'] = {} self.obj['body']['mandatory_parameters'] = {} self.obj['body']['mandatory_parameters']['system_id'] = system_id class BindTransmitterResp(BindResp): def __init__(self, sequence_number, + command_status="ESME_ROK", **kwargs): - super(BindTransmitterResp, self).__init__('bind_transmitter_resp', sequence_number, **kwargs) + super(BindTransmitterResp, self).__init__('bind_transmitter_resp', command_status, sequence_number, **kwargs) class BindReceiverResp(BindResp): def __init__(self, sequence_number, + command_status="ESME_ROK", **kwargs): - super(BindReceiverResp, self).__init__('bind_receiver_resp', sequence_number, **kwargs) + super(BindReceiverResp, self).__init__('bind_receiver_resp', command_status, sequence_number, **kwargs) class BindTransceiverResp(BindResp): def __init__(self, sequence_number, + command_status="ESME_ROK", **kwargs): - super(BindTransceiverResp, self).__init__('bind_transceiver_resp', sequence_number, **kwargs) + super(BindTransceiverResp, self).__init__('bind_transceiver_resp', command_status, sequence_number, **kwargs) class Unbind(PDU): def __init__(self, sequence_number, **kwargs): super(Unbind, self).__init__('unbind', 'ESME_ROK', sequence_number, **kwargs) class SM1(PDU): def __init__(self, command_id, sequence_number, service_type = '', source_addr_ton = 0, source_addr_npi = 0, source_addr = '', esm_class = 0, protocol_id = 0, priority_flag = 0, schedule_delivery_time = '', validity_period = '', registered_delivery = 0, replace_if_present_flag = 0, data_coding = 0, sm_default_msg_id = 0, sm_length = 0, short_message = None, **kwargs): super(SM1, self).__init__( command_id, 'ESME_ROK', sequence_number, ) self.obj['body'] = {} self.obj['body']['mandatory_parameters'] = {} self.obj['body']['mandatory_parameters']['service_type'] = service_type self.obj['body']['mandatory_parameters']['source_addr_ton'] = source_addr_ton self.obj['body']['mandatory_parameters']['source_addr_npi'] = source_addr_npi self.obj['body']['mandatory_parameters']['source_addr'] = source_addr self.obj['body']['mandatory_parameters']['esm_class'] = esm_class self.obj['body']['mandatory_parameters']['protocol_id'] = protocol_id self.obj['body']['mandatory_parameters']['priority_flag'] = priority_flag self.obj['body']['mandatory_parameters']['schedule_delivery_time'] = schedule_delivery_time self.obj['body']['mandatory_parameters']['validity_period'] = validity_period self.obj['body']['mandatory_parameters']['registered_delivery'] = registered_delivery self.obj['body']['mandatory_parameters']['replace_if_present_flag'] = replace_if_present_flag self.obj['body']['mandatory_parameters']['data_coding'] = data_coding self.obj['body']['mandatory_parameters']['sm_default_msg_id'] = sm_default_msg_id self.obj['body']['mandatory_parameters']['sm_length'] = sm_length self.obj['body']['mandatory_parameters']['short_message'] = short_message def add_message_payload(self, value): self.obj['body']['mandatory_parameters']['sm_length'] = 0 self.obj['body']['mandatory_parameters']['short_message'] = None self._PDU__add_optional_parameter('message_payload', value) class SubmitMulti(SM1): def __init__(self, sequence_number, number_of_dests = 0, dest_address = [], **kwargs): super(SubmitMulti, self).__init__('submit_multi', sequence_number, **kwargs) mandatory_parameters = self.obj['body']['mandatory_parameters'] mandatory_parameters['number_of_dests'] = number_of_dests mandatory_parameters['dest_address'] = [] + dest_address def addDestinationAddress(self, destination_addr, dest_addr_ton = 0, dest_addr_npi = 0, ): if isinstance(destination_addr, str) and len(destination_addr) > 0: new_entry = { 'dest_flag':1, 'dest_addr_ton':dest_addr_ton, 'dest_addr_npi':dest_addr_npi, 'destination_addr':destination_addr, } mandatory_parameters = self.obj['body']['mandatory_parameters'] mandatory_parameters['dest_address'].append(new_entry) mandatory_parameters['number_of_dests'] = len( mandatory_parameters['dest_address']) return True else: return False def addDistributionList(self, dl_name, ): if isinstance(dl_name, str) and len(dl_name) > 0: new_entry = { 'dest_flag':2, 'dl_name':dl_name, } mandatory_parameters = self.obj['body']['mandatory_parameters'] mandatory_parameters['dest_address'].append(new_entry) mandatory_parameters['number_of_dests'] = len( mandatory_parameters['dest_address']) return True else: return False class SM2(SM1): def __init__(self, command_id, sequence_number, dest_addr_ton = 0, dest_addr_npi = 0, destination_addr = '', **kwargs): super(SM2, self).__init__(command_id, sequence_number, **kwargs) mandatory_parameters = self.obj['body']['mandatory_parameters'] mandatory_parameters['dest_addr_ton'] = dest_addr_ton mandatory_parameters['dest_addr_npi'] = dest_addr_npi mandatory_parameters['destination_addr'] = destination_addr class SubmitSM(SM2): def __init__(self, sequence_number, **kwargs): super(SubmitSM, self).__init__('submit_sm', sequence_number, **kwargs) class SubmitSMResp(PDU): def __init__(self, sequence_number, message_id, command_status = 'ESME_ROK', **kwargs): super(SubmitSMResp, self).__init__( 'submit_sm_resp', command_status, sequence_number, **kwargs) self.obj['body'] = {} self.obj['body']['mandatory_parameters'] = {} self.obj['body']['mandatory_parameters']['message_id'] = message_id class DeliverSM(SM2): def __init__(self, sequence_number, **kwargs): super(DeliverSM, self).__init__('deliver_sm',sequence_number, **kwargs) class DeliverSMResp(PDU): def __init__(self, sequence_number, message_id = '', command_status = 'ESME_ROK', **kwargs): super(DeliverSMResp, self).__init__( 'deliver_sm_resp', command_status, sequence_number, **kwargs) self.obj['body'] = {} self.obj['body']['mandatory_parameters'] = {} self.obj['body']['mandatory_parameters']['message_id'] = message_id class EnquireLink(PDU): def __init__(self, sequence_number, **kwargs): super(EnquireLink, self).__init__( 'enquire_link', 'ESME_ROK', sequence_number, **kwargs) class EnquireLinkResp(PDU): def __init__(self, sequence_number, **kwargs): super(EnquireLinkResp, self).__init__( 'enquire_link_resp', 'ESME_ROK', sequence_number, **kwargs) class QuerySM(PDU): def __init__(self, sequence_number, message_id, source_addr = '', source_addr_ton = 0, source_addr_npi = 0, **kwargs): super(QuerySM, self).__init__( 'query_sm', 'ESME_ROK', sequence_number, **kwargs) self.obj['body'] = {} self.obj['body']['mandatory_parameters'] = {} self.obj['body']['mandatory_parameters']['message_id'] = message_id self.obj['body']['mandatory_parameters']['source_addr'] = source_addr self.obj['body']['mandatory_parameters']['source_addr_ton'] = source_addr_ton self.obj['body']['mandatory_parameters']['source_addr_npi'] = source_addr_npi #bind = BindTransmitter(system_id='test_id', password='abc123') #print bind.get_obj() #print bind.get_hex() #print bind.get_bin() ##print json.dumps(bind.get_obj(), indent=4, sort_keys=True) ##print json.dumps(decode_pdu(bind.get_hex()), indent=4, sort_keys=True) #print json.dumps(unpack_pdu(bind.get_bin()), indent=4, sort_keys=True) #sm = SubmitSM(short_message='testing testing') #print json.dumps(unpack_pdu(sm.get_bin()), indent=4, sort_keys=True) #sm.add_message_payload('616263646566676869') #print json.dumps(unpack_pdu(sm.get_bin()), indent=4, sort_keys=True)
dmaclay/python-smpp
ac9bb6f064503935d8dc610575d3f9baef929c38
deactivate & reactivate ve
diff --git a/run-tests.sh b/run-tests.sh index 4c95d8c..90edaf5 100755 --- a/run-tests.sh +++ b/run-tests.sh @@ -1,8 +1,10 @@ #!/bin/bash virtualenv --no-site-packages ve && \ source ve/bin/activate && \ pip install -r requirements.pip && \ +deactivate +source ve/bin/activate && \ nosetests --with-doctest --with-coverage --cover-package=smpp --with-xunit && \ coverage xml smpp/* && \ pep8 --repeat --exclude '0*.py' smpp > pep8.txt && \ deactivate
dmaclay/python-smpp
98ca957d77c3c018ad9403dba0007fa674258b7d
pip install
diff --git a/run-tests.sh b/run-tests.sh index 8de14c7..c05404c 100755 --- a/run-tests.sh +++ b/run-tests.sh @@ -1,7 +1,8 @@ #!/bin/bash virtualenv --no-site-packages ve && \ source ve/bin/activate && \ +pip install -r requirements.pip nosetests --with-doctest --with-coverage --cover-package=smpp --with-xunit && \ coverage xml smpp/* && \ pep8 --repeat --exclude '0*.py' smpp > pep8.txt && \ deactivate
dmaclay/python-smpp
7373fc33808e5feda84a6bd3693e3d2f1eeb78a2
just check coverage for smpp stuff
diff --git a/run-tests.sh b/run-tests.sh index f5a229e..6dc4a6f 100755 --- a/run-tests.sh +++ b/run-tests.sh @@ -1,6 +1,6 @@ #!/bin/bash virtualenv --no-site-packages ve && \ source ve/bin/activate && \ nosetests --with-doctest --with-coverage --cover-package=smpp --with-xunit && \ -coverage xml && \ +coverage xml smpp/* && \ deactivate
dmaclay/python-smpp
70a0f53a8298bbd4d45c44a4a484570f4bd9b892
jenkins is slower than my laptop
diff --git a/tests.py b/tests.py index 810f140..ce71d8c 100644 --- a/tests.py +++ b/tests.py @@ -1,339 +1,339 @@ # -*- coding: utf-8 -*- import unittest, collections from datetime import datetime, timedelta from smpp.esme import * from smpp.clickatell import * from smpp import pdu import credentials_test try:import credentials_priv except:pass from test.pdu import pdu_objects from test import pdu_asserts from test.pdu_hex import pdu_hex_strings from test import pdu_hex_asserts def unpack_hex(pdu_hex): """Unpack PDU hex string and return it as a dictionary""" return unpack_pdu(binascii.a2b_hex(hexclean(pdu_hex))) def hexclean(dirtyhex): """Remove whitespace, comments & newlines from hex string""" return re.sub(r'\s','',re.sub(r'#.*\n','\n',dirtyhex)) def prettydump(pdu_obj): """Unpack PDU dictionary and dump it as a JSON formatted string""" return json.dumps(pdu_obj, indent=4, sort_keys=True) def hex_to_named(dictionary): """ Recursive function to convert values in test dictionaries to their named counterparts that unpack_pdu returns """ clone = dictionary.copy() for key, value in clone.items(): if isinstance(value, collections.Mapping): clone[key] = hex_to_named(value) else: lookup_table = pdu.maps.get('%s_by_hex' % key) if lookup_table: # overwrite with mapped value or keep using # default if the dictionary key doesn't exist clone[key] = lookup_table.get("%.2d" % value, value) return clone def create_pdu_asserts(): pdu_index = 0 for pdu in pdu_objects: pdu_index += 1 pstr = "\n########################################\n" pstr += "pdu_json_" pstr += ('%010d' % pdu_index) pstr += " = '''" pstr += prettydump(unpack_pdu(pack_pdu(pdu))) pstr += "'''" print pstr def create_pdu_hex_asserts(): pdu_index = 0 for pdu_hex in pdu_hex_strings: pdu_index += 1 pstr = "\n########################################\n" pstr += "pdu_json_" pstr += ('%010d' % pdu_index) pstr += " = '''" pstr += prettydump(unpack_hex(pdu_hex)) pstr += "'''" print pstr ## :w|!python % > test/pdu_asserts.py #create_pdu_asserts() #quit() ## :w|!python % > test/pdu_hex_asserts.py #create_pdu_hex_asserts() #quit() class PduTestCase(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def assertDictEquals(self, dictionary1, dictionary2, depth=[]): """ Recursive dictionary comparison, will fail if any keys and values in the two dictionaries don't match. Displays the key chain / depth and which parts of the two dictionaries didn't match. """ d1_keys = dictionary1.keys() d1_keys.sort() d2_keys = dictionary2.keys() d2_keys.sort() self.failUnlessEqual(d1_keys, d2_keys, "Dictionary keys do not match, %s vs %s" % ( d1_keys, d2_keys)) for key, value in dictionary1.items(): if isinstance(value, collections.Mapping): # go recursive depth.append(key) self.assertDictEquals(value, dictionary2[key], depth) else: self.failUnlessEqual(value, dictionary2[key], "Dictionary values do not match for key '%s' " \ "(%s vs %s) at depth: %s.\nDictionary 1: %s\n" \ "Dictionary 2: %s\n" % ( key, value, dictionary2[key], ".".join(depth), prettydump(dictionary1), prettydump(dictionary2))) def test_pack_unpack_pdu_objects(self): print '' """ Take a dictionary, pack and unpack it and dump it as JSON correctly """ pdu_index = 0 for pdu in pdu_objects: pdu_index += 1 padded_index = '%010d' % pdu_index print '...', padded_index self.assertEquals( re.sub('\n *','', prettydump(unpack_pdu(pack_pdu(pdu)))), re.sub('\n *','', eval('pdu_asserts.pdu_json_'+padded_index))) def test_pack_unpack_pdu_hex_strings(self): print '' """ Read the hex data, clean it, and unpack it to JSON correctly """ pdu_index = 0 for pdu_hex in pdu_hex_strings: pdu_index += 1 padded_index = '%010d' % pdu_index print '...', padded_index self.assertEquals( re.sub('\n *','', prettydump(unpack_hex(pdu_hex))), re.sub('\n *','', eval('pdu_hex_asserts.pdu_json_'+padded_index))) def test_pack_unpack_performance(self): print '' """ Pack & unpack 2000 submit_sm PDUs in under 1 second """ submit_sm = { 'header': { 'command_length': 0, 'command_id': 'submit_sm', 'command_status': 'ESME_ROK', 'sequence_number': 0, }, 'body': { 'mandatory_parameters': { 'service_type':'', 'source_addr_ton':1, 'source_addr_npi':1, 'source_addr':'', 'dest_addr_ton':1, 'dest_addr_npi':1, 'destination_addr':'', 'esm_class':0, 'protocol_id':0, 'priority_flag':0, 'schedule_delivery_time':'', 'validity_period':'', 'registered_delivery':0, 'replace_if_present_flag':0, 'data_coding':0, 'sm_default_msg_id':0, 'sm_length':1, 'short_message':'', }, }, } start = datetime.now() - for x in range(1000): + for x in range(500): x += 1 submit_sm['header']['sequence_number'] = x sm = 'testing: x = '+str(x)+'' submit_sm['body']['mandatory_parameters']['short_message'] = sm u = unpack_pdu(pack_pdu(submit_sm)) delta = datetime.now() - start print '... 1000 pack & unpacks in:', delta self.assertTrue(delta < timedelta(seconds=1)) def test_pack_unpack_of_unicode(self): """ SMPP module should be able to pack & unpack unicode characters without a problem """ submit_sm = { 'header': { 'command_length': 67, 'command_id': 'submit_sm', 'command_status': 'ESME_ROK', 'sequence_number': 0, }, 'body': { 'mandatory_parameters': { 'service_type':'', 'source_addr_ton':'international', 'source_addr_npi':'unknown', 'source_addr':'', 'dest_addr_ton':'international', 'dest_addr_npi':'unknown', 'destination_addr':'', 'esm_class':0, 'protocol_id':0, 'priority_flag':0, 'schedule_delivery_time':'', 'validity_period':'', 'registered_delivery':0, 'replace_if_present_flag':0, 'data_coding':0, 'sm_default_msg_id':0, 'sm_length':34, 'short_message':u'Vumi says: أبن الشرموطة'.encode('utf-8'), }, }, } self.assertDictEquals( hex_to_named(submit_sm), unpack_pdu(pack_pdu(submit_sm)) ) def test_pack_unpack_of_ascii_and_unicode_8_16_32(self): """ SMPP module should be able to pack & unpack unicode characters without a problem """ submit_sm = { 'header': { 'command_length': 65, 'command_id': 'submit_sm', 'command_status': 'ESME_ROK', 'sequence_number': 0, }, 'body': { 'mandatory_parameters': { 'service_type':'', 'source_addr_ton':'international', 'source_addr_npi':'unknown', 'source_addr':'', 'dest_addr_ton':'international', 'dest_addr_npi':'unknown', 'destination_addr':'', 'esm_class':0, 'protocol_id':0, 'priority_flag':0, 'schedule_delivery_time':'', 'validity_period':'', 'registered_delivery':0, 'replace_if_present_flag':0, 'data_coding':0, 'sm_default_msg_id':0, 'sm_length':32, 'short_message':u'a \xf0\x20\u0373\u0020\u0433\u0020\u0533\u0020\u05f3\u0020\u0633\u0020\u13a3\u0020\u16a3 \U0001f090'.encode('utf-8'), }, }, } self.assertDictEquals( hex_to_named(submit_sm), unpack_pdu(pack_pdu(submit_sm)) ) class PduBuilderTestCase(unittest.TestCase): def test_true(self): print '' self.assertTrue(True) if __name__ == '__main__': print '\n##########################################################\n' #deliv_sm_resp = DeliverSMResp(23) #print deliv_sm_resp.get_obj() #print deliv_sm_resp.get_hex() #enq_lnk = EnquireLink(7) #print enq_lnk.get_obj() #print enq_lnk.get_hex() #sub_sm = SubmitSM(5, short_message='testing testing') #print sub_sm.get_obj() #print sub_sm.get_hex() #sub_sm.add_message_payload('01020304') #print sub_sm.get_obj() #print sub_sm.get_hex() #print unpack_pdu(sub_sm.get_bin()) print '\n##########################################################\n' esme = ESME() esme.loadDefaults(clickatell_defaults) esme.loadDefaults(credentials_test.logica) print esme.defaults esme.bind_transmitter() print esme.state start = datetime.now() for x in range(1): esme.submit_sm( short_message = 'gobbledygook', destination_addr = '555', ) print esme.state for x in range(1): esme.submit_multi( short_message = 'gobbledygook', dest_address = ['444','333'], ) print esme.state for x in range(1): esme.submit_multi( short_message = 'gobbledygook', dest_address = [ {'dest_flag':1, 'destination_addr':'111'}, {'dest_flag':2, 'dl_name':'list22222'}, ], ) print esme.state delta = datetime.now() - start esme.disconnect() print esme.state print 'excluding binding ... time to send messages =', delta #if __name__ == '__main__': #unittest.main()
dmaclay/python-smpp
79d27ffc647ece28621f5b4bdcb25908001948a3
fix & test for short_message == None in detect_multipart
diff --git a/smpp/pdu_inspector.py b/smpp/pdu_inspector.py index 3c83fdd..5549aab 100644 --- a/smpp/pdu_inspector.py +++ b/smpp/pdu_inspector.py @@ -1,121 +1,125 @@ from pdu import * def detect_multipart(pdu): to_msisdn = pdu['body']['mandatory_parameters']['destination_addr'] from_msisdn = pdu['body']['mandatory_parameters']['source_addr'] short_message = pdu['body']['mandatory_parameters']['short_message'] optional_parameters = {} for d in pdu['body'].get('optional_parameters',[]): optional_parameters[d['tag']] = d['value'] #print repr(pdu) try: mdict = {'multipart_type':'TLV'} mdict['to_msisdn'] = to_msisdn mdict['from_msisdn'] = from_msisdn mdict['reference_number'] = optional_parameters['sar_msg_ref_num'] mdict['total_number'] = optional_parameters['sar_total_segments'] mdict['part_number'] = optional_parameters['sar_segment_seqnum'] mdict['part_message'] = short_message return mdict except: pass + # all other multipart types will fail on short_message == None + if short_message == None: + return None + if (short_message[0:1] == '\x00' and short_message[1:2] == '\x03' and len(short_message) >= 5): mdict = {'multipart_type':'SAR'} mdict['to_msisdn'] = to_msisdn mdict['from_msisdn'] = from_msisdn mdict['reference_number'] = int(binascii.b2a_hex(short_message[2:3]), 16) mdict['total_number'] = int(binascii.b2a_hex(short_message[3:4]), 16) mdict['part_number'] = int(binascii.b2a_hex(short_message[4:5]), 16) mdict['part_message'] = short_message[5:] return mdict if (short_message[0:1] == '\x05' and short_message[1:2] == '\x00' and short_message[2:3] == '\x03' and len(short_message) >= 6): mdict = {'multipart_type':'CSM'} mdict['to_msisdn'] = to_msisdn mdict['from_msisdn'] = from_msisdn mdict['reference_number'] = int(binascii.b2a_hex(short_message[3:4]), 16) mdict['total_number'] = int(binascii.b2a_hex(short_message[4:5]), 16) mdict['part_number'] = int(binascii.b2a_hex(short_message[5:6]), 16) mdict['part_message'] = short_message[6:] return mdict if (short_message[0:1] == '\x06' and short_message[1:2] == '\x00' and short_message[2:3] == '\x04' and len(short_message) >= 7): mdict = {'multipart_type':'CSM16'} mdict['to_msisdn'] = to_msisdn mdict['from_msisdn'] = from_msisdn mdict['reference_number'] = int(binascii.b2a_hex(short_message[3:5]), 16) mdict['total_number'] = int(binascii.b2a_hex(short_message[5:6]), 16) mdict['part_number'] = int(binascii.b2a_hex(short_message[6:7]), 16) mdict['part_message'] = short_message[7:] return mdict return None def multipart_key(multipart, delimiter='_'): key_list = [] key_list.append(str(multipart.get('from_msisdn'))) key_list.append(str(multipart.get('to_msisdn'))) key_list.append(str(multipart.get('reference_number'))) key_list.append(str(multipart.get('total_number'))) return delimiter.join(key_list) class MultipartMessage: def __init__(self, array=None): self.array = {} for k,v in (array or {}).items(): self.array.update({int(k):v}) def add_pdu(self, pdu): part = detect_multipart(pdu) if part: self.array[part['part_number']] = part return True else: return False def get_partial(self): items = self.array.items() message = ''.join([i[1]['part_message'] for i in items]) to_msisdn = from_msisdn = '' if len(items): to_msisdn = items[0][1].get('to_msisdn') from_msisdn = items[0][1].get('from_msisdn') return {'to_msisdn':to_msisdn, 'from_msisdn':from_msisdn, 'message':message} def get_completed(self): items = self.array.items() if len(items) and len(items) == items[0][1].get('total_number'): return self.get_partial() return None def get_key(self, delimiter = '_'): items = self.array.items() if len(items): return multipart_key(items[0][1], delimiter) return None def get_array(self): return self.array diff --git a/test/test_multipart.py b/test/test_multipart.py index 8282069..fcca2af 100644 --- a/test/test_multipart.py +++ b/test/test_multipart.py @@ -1,74 +1,75 @@ import unittest, collections from smpp.pdu_builder import * from smpp.pdu_inspector import * class MultipartTestCase(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_formats(self): """ Testing TLV vs SAR vs CSM vs CSM16 """ tlv = DeliverSM(1, short_message='the first message part') tlv.set_sar_msg_ref_num(65017) tlv.set_sar_total_segments(2) tlv.set_sar_segment_seqnum(1) sar = DeliverSM(1, short_message='\x00\x03\xff\x02\x01the first message part') csm = DeliverSM(1, short_message='\x05\x00\x03\xff\x02\x01the first message part') csm16 = DeliverSM(1, short_message='\x06\x00\x04\xff\xff\x02\x01the first message part') non_multi = DeliverSM(1, short_message='whatever') + none_short_message = DeliverSM(1, short_message=None) self.assertEquals(detect_multipart(unpack_pdu(tlv.get_bin()))['multipart_type'], 'TLV') self.assertEquals(detect_multipart(unpack_pdu(sar.get_bin()))['multipart_type'], 'SAR') self.assertEquals(detect_multipart(unpack_pdu(csm.get_bin()))['multipart_type'], 'CSM') self.assertEquals(detect_multipart(unpack_pdu(csm16.get_bin()))['multipart_type'], 'CSM16') - self.assertEquals(detect_multipart(unpack_pdu(non_multi.get_bin())), None) + self.assertEquals(detect_multipart(unpack_pdu(none_short_message.get_bin())), None) def test_ordering(self): """ Out of order pieces must be re-assembled in-order """ sar_1 = DeliverSM(1, short_message='\x00\x03\xff\x04\x01There she was just a') sar_2 = DeliverSM(1, short_message='\x00\x03\xff\x04\x02 walking down the street,') sar_3 = DeliverSM(1, short_message='\x00\x03\xff\x04\x03 singing doo wa diddy') sar_4 = DeliverSM(1, short_message='\x00\x03\xff\x04\x04 diddy dum diddy do') multi = MultipartMessage() multi.add_pdu(sar_3.get_obj()) multi.add_pdu(sar_4.get_obj()) multi.add_pdu(sar_2.get_obj()) multi.add_pdu(sar_1.get_obj()) self.assertEquals(multi.get_completed()['message'], 'There she was just a walking down the street, singing doo wa diddy diddy dum diddy do') def test_real_csm_data(self): """ Test with real-world data which uses the CSM format. """ asif_1 = {'body': {'mandatory_parameters': {'priority_flag': 0, 'source_addr': '261xxx720371', 'protocol_id': 0, 'replace_if_present_flag': 0, 'registered_delivery': 0, 'dest_addr_ton': 'international', 'source_addr_npi': 'ISDN', 'schedule_delivery_time': '', 'dest_addr_npi': 'ISDN', 'sm_length': 159, 'esm_class': 64, 'data_coding': 0, 'service_type': '', 'source_addr_ton': 'international', 'sm_default_msg_id': 0, 'validity_period': '', 'destination_addr': '261xxx782943', 'short_message': '\x05\x00\x03\x1a\x02\x01I try to send sms testing vumi sms sms sms sms msm sms sms sms sms sms sms sms sms sms ssms sms smS sms sms sms sms sms sms sms sns sns sms sms sms sms s'}, 'optional_parameters': [{'length': 2, 'tag': 'user_message_reference', 'value': 91}, {'length': 16, 'tag': 'dest_subaddress', 'value': 'a0000410020601030303070802090403'}]}, 'header': {'command_status': 'ESME_ROK', 'command_length': 242, 'sequence_number': 23, 'command_id': 'deliver_sm'}} asif_2 = {'body': {'mandatory_parameters': {'priority_flag': 1, 'source_addr': '261xxx720371', 'protocol_id': 0, 'replace_if_present_flag': 0, 'registered_delivery': 0, 'dest_addr_ton': 'international', 'source_addr_npi': 'ISDN', 'schedule_delivery_time': '', 'dest_addr_npi': 'ISDN', 'sm_length': 78, 'esm_class': 64, 'data_coding': 0, 'service_type': '', 'source_addr_ton': 'international', 'sm_default_msg_id': 0, 'validity_period': '', 'destination_addr': '261xxx782943', 'short_message': '\x05\x00\x03\x1a\x02\x02mns again again again again again again again again sms sms sms sms sms '}, 'optional_parameters': [{'length': 2, 'tag': 'user_message_reference', 'value': 92}, {'length': 16, 'tag': 'dest_subaddress', 'value': 'a0000410020601030303070802090403'}]}, 'header': {'command_status': 'ESME_ROK', 'command_length': 161, 'sequence_number': 24, 'command_id': 'deliver_sm'}} multi = MultipartMessage() self.assertEquals(multi.get_partial(), {'to_msisdn': '', 'from_msisdn': '', 'message': ''}) self.assertEquals(multi.get_completed(), None) self.assertEquals(multi.get_key(), None) multi.add_pdu(asif_2) self.assertEquals(multi.get_partial(), {'to_msisdn': '261xxx782943', 'from_msisdn': '261xxx720371', 'message': 'mns again again again again again again again again sms sms sms sms sms '}) self.assertEquals(multi.get_completed(), None) self.assertEquals(multi.get_key(), '261xxx720371_261xxx782943_26_2') multi.add_pdu(asif_1) self.assertEquals(multi.get_completed()['message'], 'I try to send sms testing vumi sms sms sms sms msm sms sms sms sms sms sms sms sms sms ssms sms smS sms sms sms sms sms sms sms sns sns sms sms sms sms smns again again again again again again again again sms sms sms sms sms ') self.assertEquals(multi.get_key(), '261xxx720371_261xxx782943_26_2')
dmaclay/python-smpp
ca437b6dcffc2f6aa6635891833e86bc0707e122
thank you Parand
diff --git a/README.rst b/README.rst index 5f07f5b..4fb465d 100644 --- a/README.rst +++ b/README.rst @@ -1,19 +1,19 @@ Python SMPP =========== An SMPP version 3.4 library written in Python, suitable for use in Twisted_. To get started with development:: - $ virtualenv --no-site-packges ve/ + $ virtualenv --no-site-packages ve/ $ source ve/bin/activate (ve)$ pip install -r requirements.pip (ve)$ python >>> import smpp >>> Run the tests with nose (ve)$ nosetests .. _Twisted: http://www.twistedmatrix.com
dmaclay/python-smpp
00613934c9f0ed748aa04372332b08833090459e
force int keys on array reload
diff --git a/smpp/pdu_inspector.py b/smpp/pdu_inspector.py index b3bdb3a..a88f61d 100644 --- a/smpp/pdu_inspector.py +++ b/smpp/pdu_inspector.py @@ -1,119 +1,121 @@ from pdu import * def detect_multipart(pdu): to_msisdn = pdu['body']['mandatory_parameters']['destination_addr'] from_msisdn = pdu['body']['mandatory_parameters']['source_addr'] short_message = pdu['body']['mandatory_parameters']['short_message'] optional_parameters = {} for d in pdu['body'].get('optional_parameters',[]): optional_parameters[d['tag']] = d['value'] #print repr(pdu) try: mdict = {'multipart_type':'TLV'} mdict['to_msisdn'] = to_msisdn mdict['from_msisdn'] = from_msisdn mdict['reference_number'] = optional_parameters['sar_msg_ref_num'] mdict['total_number'] = optional_parameters['sar_total_segments'] mdict['part_number'] = optional_parameters['sar_segment_seqnum'] mdict['part_message'] = short_message return mdict except: pass if (short_message[0:1] == '\x00' and short_message[1:2] == '\x03' and len(short_message) >= 5): mdict = {'multipart_type':'SAR'} mdict['to_msisdn'] = to_msisdn mdict['from_msisdn'] = from_msisdn mdict['reference_number'] = int(binascii.b2a_hex(short_message[2:3]), 16) mdict['total_number'] = int(binascii.b2a_hex(short_message[3:4]), 16) mdict['part_number'] = int(binascii.b2a_hex(short_message[4:5]), 16) mdict['part_message'] = short_message[5:] return mdict if (short_message[0:1] == '\x05' and short_message[1:2] == '\x00' and short_message[2:3] == '\x03' and len(short_message) >= 6): mdict = {'multipart_type':'CSM'} mdict['to_msisdn'] = to_msisdn mdict['from_msisdn'] = from_msisdn mdict['reference_number'] = int(binascii.b2a_hex(short_message[3:4]), 16) mdict['total_number'] = int(binascii.b2a_hex(short_message[4:5]), 16) mdict['part_number'] = int(binascii.b2a_hex(short_message[5:6]), 16) mdict['part_message'] = short_message[6:] return mdict if (short_message[0:1] == '\x06' and short_message[1:2] == '\x00' and short_message[2:3] == '\x04' and len(short_message) >= 7): mdict = {'multipart_type':'CSM16'} mdict['to_msisdn'] = to_msisdn mdict['from_msisdn'] = from_msisdn mdict['reference_number'] = int(binascii.b2a_hex(short_message[3:5]), 16) mdict['total_number'] = int(binascii.b2a_hex(short_message[5:6]), 16) mdict['part_number'] = int(binascii.b2a_hex(short_message[6:7]), 16) mdict['part_message'] = short_message[7:] return mdict return None def multipart_key(multipart, delimiter='_'): key_list = [] key_list.append(str(multipart.get('from_msisdn'))) key_list.append(str(multipart.get('to_msisdn'))) key_list.append(str(multipart.get('reference_number'))) key_list.append(str(multipart.get('total_number'))) return delimiter.join(key_list) class MultipartMessage: def __init__(self, array=None): - self.array = array or {} + self.array = {} + for k,v in (array or {}).items(): + self.array.update(int(k), v) def add_pdu(self, pdu): part = detect_multipart(pdu) if part: self.array[part['part_number']] = part return True else: return False def get_partial(self): items = self.array.items() message = ''.join([i[1]['part_message'] for i in items]) to_msisdn = from_msisdn = '' if len(items): to_msisdn = items[0][1].get('to_msisdn') from_msisdn = items[0][1].get('from_msisdn') return {'to_msisdn':to_msisdn, 'from_msisdn':from_msisdn, 'message':message} def get_completed(self): items = self.array.items() if len(items) and len(items) == items[0][1].get('total_number'): return self.get_partial() return None def get_key(self, delimiter = '_'): items = self.array.items() if len(items): return multipart_key(items[0][1], delimiter) return None def get_array(self): return self.array
dmaclay/python-smpp
83d69d8381b1bb0ba2862d89d3d87fee56ed7b1a
move key calc out of class
diff --git a/smpp/pdu_inspector.py b/smpp/pdu_inspector.py index 8b8b836..b3bdb3a 100644 --- a/smpp/pdu_inspector.py +++ b/smpp/pdu_inspector.py @@ -1,115 +1,119 @@ from pdu import * def detect_multipart(pdu): to_msisdn = pdu['body']['mandatory_parameters']['destination_addr'] from_msisdn = pdu['body']['mandatory_parameters']['source_addr'] short_message = pdu['body']['mandatory_parameters']['short_message'] optional_parameters = {} for d in pdu['body'].get('optional_parameters',[]): optional_parameters[d['tag']] = d['value'] #print repr(pdu) try: mdict = {'multipart_type':'TLV'} mdict['to_msisdn'] = to_msisdn mdict['from_msisdn'] = from_msisdn mdict['reference_number'] = optional_parameters['sar_msg_ref_num'] mdict['total_number'] = optional_parameters['sar_total_segments'] mdict['part_number'] = optional_parameters['sar_segment_seqnum'] mdict['part_message'] = short_message return mdict except: pass if (short_message[0:1] == '\x00' and short_message[1:2] == '\x03' and len(short_message) >= 5): mdict = {'multipart_type':'SAR'} mdict['to_msisdn'] = to_msisdn mdict['from_msisdn'] = from_msisdn mdict['reference_number'] = int(binascii.b2a_hex(short_message[2:3]), 16) mdict['total_number'] = int(binascii.b2a_hex(short_message[3:4]), 16) mdict['part_number'] = int(binascii.b2a_hex(short_message[4:5]), 16) mdict['part_message'] = short_message[5:] return mdict if (short_message[0:1] == '\x05' and short_message[1:2] == '\x00' and short_message[2:3] == '\x03' and len(short_message) >= 6): mdict = {'multipart_type':'CSM'} mdict['to_msisdn'] = to_msisdn mdict['from_msisdn'] = from_msisdn mdict['reference_number'] = int(binascii.b2a_hex(short_message[3:4]), 16) mdict['total_number'] = int(binascii.b2a_hex(short_message[4:5]), 16) mdict['part_number'] = int(binascii.b2a_hex(short_message[5:6]), 16) mdict['part_message'] = short_message[6:] return mdict if (short_message[0:1] == '\x06' and short_message[1:2] == '\x00' and short_message[2:3] == '\x04' and len(short_message) >= 7): mdict = {'multipart_type':'CSM16'} mdict['to_msisdn'] = to_msisdn mdict['from_msisdn'] = from_msisdn mdict['reference_number'] = int(binascii.b2a_hex(short_message[3:5]), 16) mdict['total_number'] = int(binascii.b2a_hex(short_message[5:6]), 16) mdict['part_number'] = int(binascii.b2a_hex(short_message[6:7]), 16) mdict['part_message'] = short_message[7:] return mdict return None +def multipart_key(multipart, delimiter='_'): + key_list = [] + key_list.append(str(multipart.get('from_msisdn'))) + key_list.append(str(multipart.get('to_msisdn'))) + key_list.append(str(multipart.get('reference_number'))) + key_list.append(str(multipart.get('total_number'))) + return delimiter.join(key_list) + + class MultipartMessage: def __init__(self, array=None): self.array = array or {} def add_pdu(self, pdu): part = detect_multipart(pdu) if part: self.array[part['part_number']] = part return True else: return False def get_partial(self): items = self.array.items() message = ''.join([i[1]['part_message'] for i in items]) to_msisdn = from_msisdn = '' if len(items): to_msisdn = items[0][1].get('to_msisdn') from_msisdn = items[0][1].get('from_msisdn') return {'to_msisdn':to_msisdn, 'from_msisdn':from_msisdn, 'message':message} def get_completed(self): items = self.array.items() if len(items) and len(items) == items[0][1].get('total_number'): return self.get_partial() return None def get_key(self, delimiter = '_'): items = self.array.items() if len(items): - key_list = [] - key_list.append(str(items[0][1].get('from_msisdn'))) - key_list.append(str(items[0][1].get('to_msisdn'))) - key_list.append(str(items[0][1].get('reference_number'))) - key_list.append(str(items[0][1].get('total_number'))) - return delimiter.join(key_list) + return multipart_key(items[0][1], delimiter) return None def get_array(self): return self.array diff --git a/test/test_multipart.py b/test/test_multipart.py index d6fb0c6..8282069 100644 --- a/test/test_multipart.py +++ b/test/test_multipart.py @@ -1,72 +1,74 @@ import unittest, collections from smpp.pdu_builder import * from smpp.pdu_inspector import * class MultipartTestCase(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_formats(self): """ Testing TLV vs SAR vs CSM vs CSM16 """ tlv = DeliverSM(1, short_message='the first message part') tlv.set_sar_msg_ref_num(65017) tlv.set_sar_total_segments(2) tlv.set_sar_segment_seqnum(1) sar = DeliverSM(1, short_message='\x00\x03\xff\x02\x01the first message part') csm = DeliverSM(1, short_message='\x05\x00\x03\xff\x02\x01the first message part') csm16 = DeliverSM(1, short_message='\x06\x00\x04\xff\xff\x02\x01the first message part') + non_multi = DeliverSM(1, short_message='whatever') self.assertEquals(detect_multipart(unpack_pdu(tlv.get_bin()))['multipart_type'], 'TLV') self.assertEquals(detect_multipart(unpack_pdu(sar.get_bin()))['multipart_type'], 'SAR') self.assertEquals(detect_multipart(unpack_pdu(csm.get_bin()))['multipart_type'], 'CSM') self.assertEquals(detect_multipart(unpack_pdu(csm16.get_bin()))['multipart_type'], 'CSM16') + self.assertEquals(detect_multipart(unpack_pdu(non_multi.get_bin())), None) def test_ordering(self): """ Out of order pieces must be re-assembled in-order """ sar_1 = DeliverSM(1, short_message='\x00\x03\xff\x04\x01There she was just a') sar_2 = DeliverSM(1, short_message='\x00\x03\xff\x04\x02 walking down the street,') sar_3 = DeliverSM(1, short_message='\x00\x03\xff\x04\x03 singing doo wa diddy') sar_4 = DeliverSM(1, short_message='\x00\x03\xff\x04\x04 diddy dum diddy do') multi = MultipartMessage() multi.add_pdu(sar_3.get_obj()) multi.add_pdu(sar_4.get_obj()) multi.add_pdu(sar_2.get_obj()) multi.add_pdu(sar_1.get_obj()) self.assertEquals(multi.get_completed()['message'], 'There she was just a walking down the street, singing doo wa diddy diddy dum diddy do') def test_real_csm_data(self): """ Test with real-world data which uses the CSM format. """ asif_1 = {'body': {'mandatory_parameters': {'priority_flag': 0, 'source_addr': '261xxx720371', 'protocol_id': 0, 'replace_if_present_flag': 0, 'registered_delivery': 0, 'dest_addr_ton': 'international', 'source_addr_npi': 'ISDN', 'schedule_delivery_time': '', 'dest_addr_npi': 'ISDN', 'sm_length': 159, 'esm_class': 64, 'data_coding': 0, 'service_type': '', 'source_addr_ton': 'international', 'sm_default_msg_id': 0, 'validity_period': '', 'destination_addr': '261xxx782943', 'short_message': '\x05\x00\x03\x1a\x02\x01I try to send sms testing vumi sms sms sms sms msm sms sms sms sms sms sms sms sms sms ssms sms smS sms sms sms sms sms sms sms sns sns sms sms sms sms s'}, 'optional_parameters': [{'length': 2, 'tag': 'user_message_reference', 'value': 91}, {'length': 16, 'tag': 'dest_subaddress', 'value': 'a0000410020601030303070802090403'}]}, 'header': {'command_status': 'ESME_ROK', 'command_length': 242, 'sequence_number': 23, 'command_id': 'deliver_sm'}} asif_2 = {'body': {'mandatory_parameters': {'priority_flag': 1, 'source_addr': '261xxx720371', 'protocol_id': 0, 'replace_if_present_flag': 0, 'registered_delivery': 0, 'dest_addr_ton': 'international', 'source_addr_npi': 'ISDN', 'schedule_delivery_time': '', 'dest_addr_npi': 'ISDN', 'sm_length': 78, 'esm_class': 64, 'data_coding': 0, 'service_type': '', 'source_addr_ton': 'international', 'sm_default_msg_id': 0, 'validity_period': '', 'destination_addr': '261xxx782943', 'short_message': '\x05\x00\x03\x1a\x02\x02mns again again again again again again again again sms sms sms sms sms '}, 'optional_parameters': [{'length': 2, 'tag': 'user_message_reference', 'value': 92}, {'length': 16, 'tag': 'dest_subaddress', 'value': 'a0000410020601030303070802090403'}]}, 'header': {'command_status': 'ESME_ROK', 'command_length': 161, 'sequence_number': 24, 'command_id': 'deliver_sm'}} multi = MultipartMessage() self.assertEquals(multi.get_partial(), {'to_msisdn': '', 'from_msisdn': '', 'message': ''}) self.assertEquals(multi.get_completed(), None) self.assertEquals(multi.get_key(), None) multi.add_pdu(asif_2) self.assertEquals(multi.get_partial(), {'to_msisdn': '261xxx782943', 'from_msisdn': '261xxx720371', 'message': 'mns again again again again again again again again sms sms sms sms sms '}) self.assertEquals(multi.get_completed(), None) self.assertEquals(multi.get_key(), '261xxx720371_261xxx782943_26_2') multi.add_pdu(asif_1) self.assertEquals(multi.get_completed()['message'], 'I try to send sms testing vumi sms sms sms sms msm sms sms sms sms sms sms sms sms sms ssms sms smS sms sms sms sms sms sms sms sns sns sms sms sms sms smns again again again again again again again again sms sms sms sms sms ') self.assertEquals(multi.get_key(), '261xxx720371_261xxx782943_26_2')
dmaclay/python-smpp
7dd84f1d04c92f1a330d7490bbd711d563d7a68c
rename
diff --git a/test/multipart.py b/test/multipart.py deleted file mode 100644 index 79b799c..0000000 --- a/test/multipart.py +++ /dev/null @@ -1,37 +0,0 @@ -import operator - -from smpp.pdu_builder import * -from smpp.pdu_inspector import * -#from twisted.trial.unittest import TestCase - -tlv = DeliverSM(1, short_message='the first message part') -tlv.set_sar_msg_ref_num(65017) -tlv.set_sar_total_segments(2) -tlv.set_sar_segment_seqnum(1) -sar = DeliverSM(1, short_message='\x00\x03\xff\x02\x01the first message part') -csm = DeliverSM(1, short_message='\x05\x00\x03\xff\x02\x01the first message part') -csm16 = DeliverSM(1, short_message='\x06\x00\x04\xff\xff\x02\x01the first message part') - - -print '\n', detect_multipart(unpack_pdu(tlv.get_bin())) -print '\n', detect_multipart(unpack_pdu(sar.get_bin())) -print '\n', detect_multipart(unpack_pdu(csm.get_bin())) -print '\n', detect_multipart(unpack_pdu(csm16.get_bin())) - -sar_1 = DeliverSM(1, short_message='\x00\x03\xff\x04\x01There she was just a') -sar_2 = DeliverSM(1, short_message='\x00\x03\xff\x04\x02 walking down the street,') -sar_3 = DeliverSM(1, short_message='\x00\x03\xff\x04\x03 singing doo wa diddy') -sar_4 = DeliverSM(1, short_message='\x00\x03\xff\x04\x04 diddy dum diddy do') - -mess_list = [] -mess_list.append(detect_multipart(unpack_pdu(sar_3.get_bin()))) -mess_list.append(detect_multipart(unpack_pdu(sar_4.get_bin()))) -mess_list.append(detect_multipart(unpack_pdu(sar_2.get_bin()))) -mess_list.append(detect_multipart(unpack_pdu(sar_1.get_bin()))) - -print mess_list -print ''.join([i['part_message'] for i in mess_list]) -print '\n' -mess_list.sort(key=operator.itemgetter('part_number')) -print mess_list -print ''.join([i['part_message'] for i in mess_list]) diff --git a/test/test_multipart.py b/test/test_multipart.py new file mode 100644 index 0000000..fc1ad2b --- /dev/null +++ b/test/test_multipart.py @@ -0,0 +1,76 @@ +import operator +import unittest, collections + +from smpp.pdu_builder import * +from smpp.pdu_inspector import * + + +class MultipartTestCase(unittest.TestCase): + + def setUp(self): + pass + + def tearDown(self): + pass + + def test_formats(self): + """ + Testing TLV vs SAR vs CSM vs CSM16 + """ + tlv = DeliverSM(1, short_message='the first message part') + tlv.set_sar_msg_ref_num(65017) + tlv.set_sar_total_segments(2) + tlv.set_sar_segment_seqnum(1) + sar = DeliverSM(1, short_message='\x00\x03\xff\x02\x01the first message part') + csm = DeliverSM(1, short_message='\x05\x00\x03\xff\x02\x01the first message part') + csm16 = DeliverSM(1, short_message='\x06\x00\x04\xff\xff\x02\x01the first message part') + + self.assertEquals(detect_multipart(unpack_pdu(tlv.get_bin()))['multipart_type'], 'TLV') + self.assertEquals(detect_multipart(unpack_pdu(sar.get_bin()))['multipart_type'], 'SAR') + self.assertEquals(detect_multipart(unpack_pdu(csm.get_bin()))['multipart_type'], 'CSM') + self.assertEquals(detect_multipart(unpack_pdu(csm16.get_bin()))['multipart_type'], 'CSM16') + + + def all(self): + sar_1 = DeliverSM(1, short_message='\x00\x03\xff\x04\x01There she was just a') + sar_2 = DeliverSM(1, short_message='\x00\x03\xff\x04\x02 walking down the street,') + sar_3 = DeliverSM(1, short_message='\x00\x03\xff\x04\x03 singing doo wa diddy') + sar_4 = DeliverSM(1, short_message='\x00\x03\xff\x04\x04 diddy dum diddy do') + + mess_list = [] + mess_list.append(detect_multipart(unpack_pdu(sar_3.get_bin()))) + mess_list.append(detect_multipart(unpack_pdu(sar_4.get_bin()))) + mess_list.append(detect_multipart(unpack_pdu(sar_2.get_bin()))) + mess_list.append(detect_multipart(unpack_pdu(sar_1.get_bin()))) + + print mess_list + print ''.join([i['part_message'] for i in mess_list]) + print '\n' + mess_list.sort(key=operator.itemgetter('part_number')) + print mess_list + print ''.join([i['part_message'] for i in mess_list]) + + + + asif_1 = {'body': {'mandatory_parameters': {'priority_flag': 0, 'source_addr': '261xxx720371', 'protocol_id': 0, 'replace_if_present_flag': 0, 'registered_delivery': 0, 'dest_addr_ton': 'international', 'source_addr_npi': 'ISDN', 'schedule_delivery_time': '', 'dest_addr_npi': 'ISDN', 'sm_length': 159, 'esm_class': 64, 'data_coding': 0, 'service_type': '', 'source_addr_ton': 'international', 'sm_default_msg_id': 0, 'validity_period': '', 'destination_addr': '261xxx782943', 'short_message': '\x05\x00\x03\x1a\x02\x01I try to send sms testing vumi sms sms sms sms msm sms sms sms sms sms sms sms sms sms ssms sms smS sms sms sms sms sms sms sms sns sns sms sms sms sms s'}, 'optional_parameters': [{'length': 2, 'tag': 'user_message_reference', 'value': 91}, {'length': 16, 'tag': 'dest_subaddress', 'value': 'a0000410020601030303070802090403'}]}, 'header': {'command_status': 'ESME_ROK', 'command_length': 242, 'sequence_number': 23, 'command_id': 'deliver_sm'}} + + + + asif_2 = {'body': {'mandatory_parameters': {'priority_flag': 1, 'source_addr': '261xxx720371', 'protocol_id': 0, 'replace_if_present_flag': 0, 'registered_delivery': 0, 'dest_addr_ton': 'international', 'source_addr_npi': 'ISDN', 'schedule_delivery_time': '', 'dest_addr_npi': 'ISDN', 'sm_length': 78, 'esm_class': 64, 'data_coding': 0, 'service_type': '', 'source_addr_ton': 'international', 'sm_default_msg_id': 0, 'validity_period': '', 'destination_addr': '261xxx782943', 'short_message': '\x05\x00\x03\x1a\x02\x02mns again again again again again again again again sms sms sms sms sms '}, 'optional_parameters': [{'length': 2, 'tag': 'user_message_reference', 'value': 92}, {'length': 16, 'tag': 'dest_subaddress', 'value': 'a0000410020601030303070802090403'}]}, 'header': {'command_status': 'ESME_ROK', 'command_length': 161, 'sequence_number': 24, 'command_id': 'deliver_sm'}} + + + + multi = MultipartMessage() + print "VVVVVVVVVVVVVVV", multi.get_partial() + print "CCCCCCCCCCCCCCC", multi.get_completed() + print "KKKKKKKKKKKKKKK", multi.get_key() + multi.add_pdu(asif_2) + print "VVVVVVVVVVVVVVV", multi.get_partial() + print "CCCCCCCCCCCCCCC", multi.get_completed() + print "KKKKKKKKKKKKKKK", multi.get_key() + multi.add_pdu(asif_1) + print "VVVVVVVVVVVVVVV", multi.get_partial() + print "CCCCCCCCCCCCCCC", multi.get_completed() + print "KKKKKKKKKKKKKKK", multi.get_key() + + print '\n\n', multi.get_array()
dmaclay/python-smpp
7be667b2316b8159d507cbd3dd97382d97b074a5
multipart detection & reassembly
diff --git a/smpp/pdu_inspector.py b/smpp/pdu_inspector.py index b015e95..1dfdb46 100644 --- a/smpp/pdu_inspector.py +++ b/smpp/pdu_inspector.py @@ -1,56 +1,115 @@ from pdu import * def detect_multipart(pdu): + to_msisdn = pdu['body']['mandatory_parameters']['destination_addr'] + from_msisdn = pdu['body']['mandatory_parameters']['source_addr'] short_message = pdu['body']['mandatory_parameters']['short_message'] optional_parameters = {} for d in pdu['body'].get('optional_parameters',[]): optional_parameters[d['tag']] = d['value'] #print repr(pdu) try: mdict = {'multipart_type':'TLV'} + mdict['to_msisdn'] = to_msisdn + mdict['from_msisdn'] = from_msisdn mdict['reference_number'] = optional_parameters['sar_msg_ref_num'] mdict['total_number'] = optional_parameters['sar_total_segments'] mdict['part_number'] = optional_parameters['sar_segment_seqnum'] mdict['part_message'] = short_message return mdict except: pass if (short_message[0:1] == '\x00' and short_message[1:2] == '\x03' and len(short_message) >= 5): mdict = {'multipart_type':'SAR'} + mdict['to_msisdn'] = to_msisdn + mdict['from_msisdn'] = from_msisdn mdict['reference_number'] = int(binascii.b2a_hex(short_message[2:3]), 16) mdict['total_number'] = int(binascii.b2a_hex(short_message[3:4]), 16) mdict['part_number'] = int(binascii.b2a_hex(short_message[4:5]), 16) mdict['part_message'] = short_message[5:] return mdict if (short_message[0:1] == '\x05' and short_message[1:2] == '\x00' and short_message[2:3] == '\x03' and len(short_message) >= 6): mdict = {'multipart_type':'CSM'} + mdict['to_msisdn'] = to_msisdn + mdict['from_msisdn'] = from_msisdn mdict['reference_number'] = int(binascii.b2a_hex(short_message[3:4]), 16) mdict['total_number'] = int(binascii.b2a_hex(short_message[4:5]), 16) mdict['part_number'] = int(binascii.b2a_hex(short_message[5:6]), 16) mdict['part_message'] = short_message[6:] return mdict if (short_message[0:1] == '\x06' and short_message[1:2] == '\x00' and short_message[2:3] == '\x04' and len(short_message) >= 7): mdict = {'multipart_type':'CSM16'} + mdict['to_msisdn'] = to_msisdn + mdict['from_msisdn'] = from_msisdn mdict['reference_number'] = int(binascii.b2a_hex(short_message[3:5]), 16) mdict['total_number'] = int(binascii.b2a_hex(short_message[5:6]), 16) mdict['part_number'] = int(binascii.b2a_hex(short_message[6:7]), 16) mdict['part_message'] = short_message[7:] return mdict return None + +class MultipartMessage: + + def __init__(self, array={}): + self.array = array + + def add_pdu(self, pdu): + part = detect_multipart(pdu) + if part: + self.array[part['part_number']] = part + return True + else: + return False + + def get_partial(self): + items = self.array.items() + message = ''.join([i[1]['part_message'] for i in items]) + to_msisdn = from_msisdn = '' + if len(items): + to_msisdn = items[0][1].get('to_msisdn') + from_msisdn = items[0][1].get('from_msisdn') + return {'to_msisdn':to_msisdn, + 'from_msisdn':from_msisdn, + 'message':message} + + def get_completed(self): + items = self.array.items() + if len(items) and len(items) == items[0][1].get('total_number'): + return self.get_partial() + return None + + def get_key(self, delimiter = '_'): + items = self.array.items() + if len(items): + key_list = [] + key_list.append(str(items[0][1].get('from_msisdn'))) + key_list.append(str(items[0][1].get('to_msisdn'))) + key_list.append(str(items[0][1].get('reference_number'))) + key_list.append(str(items[0][1].get('total_number'))) + return delimiter.join(key_list) + return None + + def get_array(self): + return self.array + + + + +
dmaclay/python-smpp
eecb515c9a1a2ae96d11a1bdb515635ebb730f23
sep func & test
diff --git a/smpp/pdu_inspector.py b/smpp/pdu_inspector.py index e69de29..b015e95 100644 --- a/smpp/pdu_inspector.py +++ b/smpp/pdu_inspector.py @@ -0,0 +1,56 @@ + +from pdu import * + + +def detect_multipart(pdu): + short_message = pdu['body']['mandatory_parameters']['short_message'] + optional_parameters = {} + for d in pdu['body'].get('optional_parameters',[]): + optional_parameters[d['tag']] = d['value'] + + #print repr(pdu) + + try: + mdict = {'multipart_type':'TLV'} + mdict['reference_number'] = optional_parameters['sar_msg_ref_num'] + mdict['total_number'] = optional_parameters['sar_total_segments'] + mdict['part_number'] = optional_parameters['sar_segment_seqnum'] + mdict['part_message'] = short_message + return mdict + except: + pass + + if (short_message[0:1] == '\x00' + and short_message[1:2] == '\x03' + and len(short_message) >= 5): + mdict = {'multipart_type':'SAR'} + mdict['reference_number'] = int(binascii.b2a_hex(short_message[2:3]), 16) + mdict['total_number'] = int(binascii.b2a_hex(short_message[3:4]), 16) + mdict['part_number'] = int(binascii.b2a_hex(short_message[4:5]), 16) + mdict['part_message'] = short_message[5:] + return mdict + + if (short_message[0:1] == '\x05' + and short_message[1:2] == '\x00' + and short_message[2:3] == '\x03' + and len(short_message) >= 6): + mdict = {'multipart_type':'CSM'} + mdict['reference_number'] = int(binascii.b2a_hex(short_message[3:4]), 16) + mdict['total_number'] = int(binascii.b2a_hex(short_message[4:5]), 16) + mdict['part_number'] = int(binascii.b2a_hex(short_message[5:6]), 16) + mdict['part_message'] = short_message[6:] + return mdict + + if (short_message[0:1] == '\x06' + and short_message[1:2] == '\x00' + and short_message[2:3] == '\x04' + and len(short_message) >= 7): + mdict = {'multipart_type':'CSM16'} + mdict['reference_number'] = int(binascii.b2a_hex(short_message[3:5]), 16) + mdict['total_number'] = int(binascii.b2a_hex(short_message[5:6]), 16) + mdict['part_number'] = int(binascii.b2a_hex(short_message[6:7]), 16) + mdict['part_message'] = short_message[7:] + return mdict + + return None + diff --git a/test/multipart.py b/test/multipart.py index 0aa6ad4..79b799c 100644 --- a/test/multipart.py +++ b/test/multipart.py @@ -1,92 +1,37 @@ import operator from smpp.pdu_builder import * +from smpp.pdu_inspector import * #from twisted.trial.unittest import TestCase tlv = DeliverSM(1, short_message='the first message part') tlv.set_sar_msg_ref_num(65017) tlv.set_sar_total_segments(2) tlv.set_sar_segment_seqnum(1) sar = DeliverSM(1, short_message='\x00\x03\xff\x02\x01the first message part') csm = DeliverSM(1, short_message='\x05\x00\x03\xff\x02\x01the first message part') csm16 = DeliverSM(1, short_message='\x06\x00\x04\xff\xff\x02\x01the first message part') - -def detect_multipart(pdu): - short_message = pdu['body']['mandatory_parameters']['short_message'] - optional_parameters = {} - for d in pdu['body'].get('optional_parameters',[]): - optional_parameters[d['tag']] = d['value'] - - #print repr(pdu) - - try: - mdict = {'multipart_type':'TLV'} - mdict['reference_number'] = optional_parameters['sar_msg_ref_num'] - mdict['total_number'] = optional_parameters['sar_total_segments'] - mdict['part_number'] = optional_parameters['sar_segment_seqnum'] - mdict['part_message'] = short_message - return mdict - except: - pass - - if (short_message[0:1] == '\x00' - and short_message[1:2] == '\x03' - and len(short_message) >= 5): - mdict = {'multipart_type':'SAR'} - mdict['reference_number'] = int(binascii.b2a_hex(short_message[2:3]), 16) - mdict['total_number'] = int(binascii.b2a_hex(short_message[3:4]), 16) - mdict['part_number'] = int(binascii.b2a_hex(short_message[4:5]), 16) - mdict['part_message'] = short_message[5:] - return mdict - - if (short_message[0:1] == '\x05' - and short_message[1:2] == '\x00' - and short_message[2:3] == '\x03' - and len(short_message) >= 6): - mdict = {'multipart_type':'CSM'} - mdict['reference_number'] = int(binascii.b2a_hex(short_message[3:4]), 16) - mdict['total_number'] = int(binascii.b2a_hex(short_message[4:5]), 16) - mdict['part_number'] = int(binascii.b2a_hex(short_message[5:6]), 16) - mdict['part_message'] = short_message[6:] - return mdict - - if (short_message[0:1] == '\x06' - and short_message[1:2] == '\x00' - and short_message[2:3] == '\x04' - and len(short_message) >= 7): - mdict = {'multipart_type':'CSM16'} - mdict['reference_number'] = int(binascii.b2a_hex(short_message[3:5]), 16) - mdict['total_number'] = int(binascii.b2a_hex(short_message[5:6]), 16) - mdict['part_number'] = int(binascii.b2a_hex(short_message[6:7]), 16) - mdict['part_message'] = short_message[7:] - return mdict - - return None - - - - print '\n', detect_multipart(unpack_pdu(tlv.get_bin())) print '\n', detect_multipart(unpack_pdu(sar.get_bin())) print '\n', detect_multipart(unpack_pdu(csm.get_bin())) print '\n', detect_multipart(unpack_pdu(csm16.get_bin())) sar_1 = DeliverSM(1, short_message='\x00\x03\xff\x04\x01There she was just a') sar_2 = DeliverSM(1, short_message='\x00\x03\xff\x04\x02 walking down the street,') sar_3 = DeliverSM(1, short_message='\x00\x03\xff\x04\x03 singing doo wa diddy') sar_4 = DeliverSM(1, short_message='\x00\x03\xff\x04\x04 diddy dum diddy do') mess_list = [] mess_list.append(detect_multipart(unpack_pdu(sar_3.get_bin()))) mess_list.append(detect_multipart(unpack_pdu(sar_4.get_bin()))) mess_list.append(detect_multipart(unpack_pdu(sar_2.get_bin()))) mess_list.append(detect_multipart(unpack_pdu(sar_1.get_bin()))) print mess_list print ''.join([i['part_message'] for i in mess_list]) print '\n' mess_list.sort(key=operator.itemgetter('part_number')) print mess_list print ''.join([i['part_message'] for i in mess_list])
dmaclay/python-smpp
4d9fd1299283d1bdd699a39a5a6c7108aa72aca2
that's better
diff --git a/smpp/pdu.py b/smpp/pdu.py index 650b1d1..207c486 100644 --- a/smpp/pdu.py +++ b/smpp/pdu.py @@ -527,516 +527,520 @@ maps['esm_class_bits'] = { 'type_1101' :'34', 'type_1110' :'38', 'type_1111' :'3a', 'feature_none' :'00', 'feature_UDHI' :'40', 'feature_reply_path' :'80', 'feature_UDHI_and_reply_path':'c0' } # Registered Delivery bits - SMPP v3.4, section 5.2.17, page 124 maps['registered_delivery_bits'] = { 'receipt_mask' :'03', 'ack_mask' :'0c', 'intermed_notif_mask' :'80', 'receipt_none' :'00', 'receipt_always' :'01', 'receipt_on_fail' :'02', 'receipt_res' :'03', 'ack_none' :'00', 'ack_delivery' :'04', 'ack_user' :'08', 'ack_delivery_and_user':'0c', 'intermed_notif_none' :'00', 'intermed_notif' :'10' } # submit_multi dest_flag constants - SMPP v3.4, section 5.2.25, page 129 #maps['dest_flag_by_name'] = { #'SME Address' :1, #'Distribution List Name':2 #} # Message State codes returned in query_sm_resp PDUs - SMPP v3.4, section 5.2.28, table 5-6, page 130 maps['message_state_by_name'] = { 'ENROUTE' :1, 'DELIVERED' :2, 'EXPIRED' :3, 'DELETED' :4, 'UNDELIVERABLE':5, 'ACCEPTED' :6, 'UNKNOWN' :7, 'REJECTED' :8 } # Facility Code bits for SMPP v4 maps['facility_code_bits'] = { 'GF_PVCY' :'00000001', 'GF_SUBADDR':'00000002', 'NF_CC' :'00080000', 'NF_PDC' :'00010000', 'NF_IS136' :'00020000', 'NF_IS95A' :'00040000' } # Optional Parameter Tags - SMPP v3.4, section 5.3.2, Table 5-7, page 132-133 optional_parameter_tag_by_hex = { '0005':{'hex':'0005', 'name':'dest_addr_subunit', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.1, page 134 '0006':{'hex':'0006', 'name':'dest_network_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.3, page 135 '0007':{'hex':'0007', 'name':'dest_bearer_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.5, page 136 '0008':{'hex':'0008', 'name':'dest_telematics_id', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.7, page 137 '000d':{'hex':'000d', 'name':'source_addr_subunit', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.2, page 134 '000e':{'hex':'000e', 'name':'source_network_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.4, page 135 '000f':{'hex':'000f', 'name':'source_bearer_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.6, page 136 '0010':{'hex':'0010', 'name':'source_telematics_id', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.8, page 137 '0017':{'hex':'0017', 'name':'qos_time_to_live', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.9, page 138 '0019':{'hex':'0019', 'name':'payload_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.10, page 138 '001d':{'hex':'001d', 'name':'additional_status_info_text', 'type':'string', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.11, page 139 '001e':{'hex':'001e', 'name':'receipted_message_id', 'type':'string', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.12, page 139 '0030':{'hex':'0030', 'name':'ms_msg_wait_facilities', 'type':'bitmask', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.13, page 140 '0101':{'hex':'0101', 'name':'PVCY_AuthenticationStr', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 58-62 '0201':{'hex':'0201', 'name':'privacy_indicator', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.14, page 141 '0202':{'hex':'0202', 'name':'source_subaddress', 'type':'hex', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.15, page 142 '0203':{'hex':'0203', 'name':'dest_subaddress', 'type':'hex', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.16, page 143 '0204':{'hex':'0204', 'name':'user_message_reference', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.17, page 143 '0205':{'hex':'0205', 'name':'user_response_code', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.18, page 144 '020a':{'hex':'020a', 'name':'source_port', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.20, page 145 '020b':{'hex':'020b', 'name':'destination_port', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.21, page 145 '020c':{'hex':'020c', 'name':'sar_msg_ref_num', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.22, page 146 '020d':{'hex':'020d', 'name':'language_indicator', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.19, page 144 '020e':{'hex':'020e', 'name':'sar_total_segments', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.23, page 147 '020f':{'hex':'020f', 'name':'sar_segment_seqnum', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.24, page 147 '0210':{'hex':'0210', 'name':'sc_interface_version', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.25, page 148 '0301':{'hex':'0301', 'name':'CC_CBN', 'type':None, 'tech':'V4'}, # v4 page 70 '0302':{'hex':'0302', 'name':'callback_num_pres_ind', 'type':'bitmask', 'tech':'TDMA'}, # SMPP v3.4, section 5.3.2.37, page 156 '0303':{'hex':'0303', 'name':'callback_num_atag', 'type':'hex', 'tech':'TDMA'}, # SMPP v3.4, section 5.3.2.38, page 157 '0304':{'hex':'0304', 'name':'number_of_messages', 'type':'integer', 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.39, page 158 '0381':{'hex':'0381', 'name':'callback_num', 'type':'hex', 'tech':'CDMA, TDMA, GSM, iDEN'}, # SMPP v3.4, section 5.3.2.36, page 155 '0420':{'hex':'0420', 'name':'dpf_result', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.28, page 149 '0421':{'hex':'0421', 'name':'set_dpf', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.29, page 150 '0422':{'hex':'0422', 'name':'ms_availability_status', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.30, page 151 '0423':{'hex':'0423', 'name':'network_error_code', 'type':'hex', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.31, page 152 '0424':{'hex':'0424', 'name':'message_payload', 'type':'hex', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.32, page 153 '0425':{'hex':'0425', 'name':'delivery_failure_reason', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.33, page 153 '0426':{'hex':'0426', 'name':'more_messages_to_send', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.34, page 154 '0427':{'hex':'0427', 'name':'message_state', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.35, page 154 '0428':{'hex':'0428', 'name':'congestion_state', 'type':None, 'tech':'Generic'}, '0501':{'hex':'0501', 'name':'ussd_service_op', 'type':'hex', 'tech':'GSM (USSD)'}, # SMPP v3.4, section 5.3.2.44, page 161 '0600':{'hex':'0600', 'name':'broadcast_channel_indicator', 'type':None, 'tech':'GSM'}, '0601':{'hex':'0601', 'name':'broadcast_content_type', 'type':None, 'tech':'CDMA, TDMA, GSM'}, '0602':{'hex':'0602', 'name':'broadcast_content_type_info', 'type':None, 'tech':'CDMA, TDMA'}, '0603':{'hex':'0603', 'name':'broadcast_message_class', 'type':None, 'tech':'GSM'}, '0604':{'hex':'0604', 'name':'broadcast_rep_num', 'type':None, 'tech':'GSM'}, '0605':{'hex':'0605', 'name':'broadcast_frequency_interval', 'type':None, 'tech':'CDMA, TDMA, GSM'}, '0606':{'hex':'0606', 'name':'broadcast_area_identifier', 'type':None, 'tech':'CDMA, TDMA, GSM'}, '0607':{'hex':'0607', 'name':'broadcast_error_status', 'type':None, 'tech':'CDMA, TDMA, GSM'}, '0608':{'hex':'0608', 'name':'broadcast_area_success', 'type':None, 'tech':'GSM'}, '0609':{'hex':'0609', 'name':'broadcast_end_time', 'type':None, 'tech':'CDMA, TDMA, GSM'}, '060a':{'hex':'060a', 'name':'broadcast_service_group', 'type':None, 'tech':'CDMA, TDMA'}, '060b':{'hex':'060b', 'name':'billing_identification', 'type':None, 'tech':'Generic'}, '060d':{'hex':'060d', 'name':'source_network_id', 'type':None, 'tech':'Generic'}, '060e':{'hex':'060e', 'name':'dest_network_id', 'type':None, 'tech':'Generic'}, '060f':{'hex':'060f', 'name':'source_node_id', 'type':None, 'tech':'Generic'}, '0610':{'hex':'0610', 'name':'dest_node_id', 'type':None, 'tech':'Generic'}, '0611':{'hex':'0611', 'name':'dest_addr_np_resolution', 'type':None, 'tech':'CDMA, TDMA (US Only)'}, '0612':{'hex':'0612', 'name':'dest_addr_np_information', 'type':None, 'tech':'CDMA, TDMA (US Only)'}, '0613':{'hex':'0613', 'name':'dest_addr_np_country', 'type':None, 'tech':'CDMA, TDMA (US Only)'}, '1101':{'hex':'1101', 'name':'PDC_MessageClass', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 75 '1102':{'hex':'1102', 'name':'PDC_PresentationOption', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 76 '1103':{'hex':'1103', 'name':'PDC_AlertMechanism', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 76 '1104':{'hex':'1104', 'name':'PDC_Teleservice', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 77 '1105':{'hex':'1105', 'name':'PDC_MultiPartMessage', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 77 '1106':{'hex':'1106', 'name':'PDC_PredefinedMsg', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 78 '1201':{'hex':'1201', 'name':'display_time', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.26, page 148 '1203':{'hex':'1203', 'name':'sms_signal', 'type':'integer', 'tech':'TDMA'}, # SMPP v3.4, section 5.3.2.40, page 158 '1204':{'hex':'1204', 'name':'ms_validity', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.27, page 149 '1304':{'hex':'1304', 'name':'IS95A_AlertOnDelivery', 'type':None, 'tech':'CDMA'}, # v4 page 85 '1306':{'hex':'1306', 'name':'IS95A_LanguageIndicator', 'type':None, 'tech':'CDMA'}, # v4 page 86 '130c':{'hex':'130c', 'name':'alert_on_message_delivery', 'type':None, 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.41, page 159 '1380':{'hex':'1380', 'name':'its_reply_type', 'type':'integer', 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.42, page 159 '1383':{'hex':'1383', 'name':'its_session_info', 'type':'hex', 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.43, page 160 '1402':{'hex':'1402', 'name':'operator_id', 'type':None, 'tech':'vendor extension'}, '1403':{'hex':'1403', 'name':'tariff', 'type':None, 'tech':'Mobile Network Code vendor extension'}, '1450':{'hex':'1450', 'name':'mcc', 'type':None, 'tech':'Mobile Country Code vendor extension'}, '1451':{'hex':'1451', 'name':'mnc', 'type':None, 'tech':'Mobile Network Code vendor extension'} } def optional_parameter_tag_name_by_hex(x): return optional_parameter_tag_by_hex.get(x,{}).get('name') def optional_parameter_tag_type_by_hex(x): return optional_parameter_tag_by_hex.get(x,{}).get('type') optional_parameter_tag_by_name = { 'dest_addr_subunit' :{'hex':'0005', 'name':'dest_addr_subunit', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.1, page 134 'dest_network_type' :{'hex':'0006', 'name':'dest_network_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.3, page 135 'dest_bearer_type' :{'hex':'0007', 'name':'dest_bearer_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.5, page 136 'dest_telematics_id' :{'hex':'0008', 'name':'dest_telematics_id', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.7, page 137 'source_addr_subunit' :{'hex':'000d', 'name':'source_addr_subunit', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.2, page 134 'source_network_type' :{'hex':'000e', 'name':'source_network_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.4, page 135 'source_bearer_type' :{'hex':'000f', 'name':'source_bearer_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.6, page 136 'source_telematics_id' :{'hex':'0010', 'name':'source_telematics_id', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.8, page 137 'qos_time_to_live' :{'hex':'0017', 'name':'qos_time_to_live', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.9, page 138 'payload_type' :{'hex':'0019', 'name':'payload_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.10, page 138 'additional_status_info_text' :{'hex':'001d', 'name':'additional_status_info_text', 'type':'string', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.11, page 139 'receipted_message_id' :{'hex':'001e', 'name':'receipted_message_id', 'type':'string', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.12, page 139 'ms_msg_wait_facilities' :{'hex':'0030', 'name':'ms_msg_wait_facilities', 'type':'bitmask', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.13, page 140 'PVCY_AuthenticationStr' :{'hex':'0101', 'name':'PVCY_AuthenticationStr', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 58-62 'privacy_indicator' :{'hex':'0201', 'name':'privacy_indicator', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.14, page 141 'source_subaddress' :{'hex':'0202', 'name':'source_subaddress', 'type':'hex', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.15, page 142 'dest_subaddress' :{'hex':'0203', 'name':'dest_subaddress', 'type':'hex', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.16, page 143 'user_message_reference' :{'hex':'0204', 'name':'user_message_reference', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.17, page 143 'user_response_code' :{'hex':'0205', 'name':'user_response_code', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.18, page 144 'source_port' :{'hex':'020a', 'name':'source_port', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.20, page 145 'destination_port' :{'hex':'020b', 'name':'destination_port', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.21, page 145 'sar_msg_ref_num' :{'hex':'020c', 'name':'sar_msg_ref_num', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.22, page 146 'language_indicator' :{'hex':'020d', 'name':'language_indicator', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.19, page 144 'sar_total_segments' :{'hex':'020e', 'name':'sar_total_segments', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.23, page 147 'sar_segment_seqnum' :{'hex':'020f', 'name':'sar_segment_seqnum', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.24, page 147 'sc_interface_version' :{'hex':'0210', 'name':'sc_interface_version', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.25, page 148 'CC_CBN' :{'hex':'0301', 'name':'CC_CBN', 'type':None, 'tech':'V4'}, # v4 page 70 'callback_num_pres_ind' :{'hex':'0302', 'name':'callback_num_pres_ind', 'type':'bitmask', 'tech':'TDMA'}, # SMPP v3.4, section 5.3.2.37, page 156 'callback_num_atag' :{'hex':'0303', 'name':'callback_num_atag', 'type':'hex', 'tech':'TDMA'}, # SMPP v3.4, section 5.3.2.38, page 157 'number_of_messages' :{'hex':'0304', 'name':'number_of_messages', 'type':'integer', 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.39, page 158 'callback_num' :{'hex':'0381', 'name':'callback_num', 'type':'hex', 'tech':'CDMA, TDMA, GSM, iDEN'}, # SMPP v3.4, section 5.3.2.36, page 155 'dpf_result' :{'hex':'0420', 'name':'dpf_result', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.28, page 149 'set_dpf' :{'hex':'0421', 'name':'set_dpf', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.29, page 150 'ms_availability_status' :{'hex':'0422', 'name':'ms_availability_status', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.30, page 151 'network_error_code' :{'hex':'0423', 'name':'network_error_code', 'type':'hex', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.31, page 152 'message_payload' :{'hex':'0424', 'name':'message_payload', 'type':'hex', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.32, page 153 'delivery_failure_reason' :{'hex':'0425', 'name':'delivery_failure_reason', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.33, page 153 'more_messages_to_send' :{'hex':'0426', 'name':'more_messages_to_send', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.34, page 154 'message_state' :{'hex':'0427', 'name':'message_state', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.35, page 154 'congestion_state' :{'hex':'0428', 'name':'congestion_state', 'type':None, 'tech':'Generic'}, 'ussd_service_op' :{'hex':'0501', 'name':'ussd_service_op', 'type':'hex', 'tech':'GSM (USSD)'}, # SMPP v3.4, section 5.3.2.44, page 161 'broadcast_channel_indicator' :{'hex':'0600', 'name':'broadcast_channel_indicator', 'type':None, 'tech':'GSM'}, 'broadcast_content_type' :{'hex':'0601', 'name':'broadcast_content_type', 'type':None, 'tech':'CDMA, TDMA, GSM'}, 'broadcast_content_type_info' :{'hex':'0602', 'name':'broadcast_content_type_info', 'type':None, 'tech':'CDMA, TDMA'}, 'broadcast_message_class' :{'hex':'0603', 'name':'broadcast_message_class', 'type':None, 'tech':'GSM'}, 'broadcast_rep_num' :{'hex':'0604', 'name':'broadcast_rep_num', 'type':None, 'tech':'GSM'}, 'broadcast_frequency_interval':{'hex':'0605', 'name':'broadcast_frequency_interval', 'type':None, 'tech':'CDMA, TDMA, GSM'}, 'broadcast_area_identifier' :{'hex':'0606', 'name':'broadcast_area_identifier', 'type':None, 'tech':'CDMA, TDMA, GSM'}, 'broadcast_error_status' :{'hex':'0607', 'name':'broadcast_error_status', 'type':None, 'tech':'CDMA, TDMA, GSM'}, 'broadcast_area_success' :{'hex':'0608', 'name':'broadcast_area_success', 'type':None, 'tech':'GSM'}, 'broadcast_end_time' :{'hex':'0609', 'name':'broadcast_end_time', 'type':None, 'tech':'CDMA, TDMA, GSM'}, 'broadcast_service_group' :{'hex':'060a', 'name':'broadcast_service_group', 'type':None, 'tech':'CDMA, TDMA'}, 'billing_identification' :{'hex':'060b', 'name':'billing_identification', 'type':None, 'tech':'Generic'}, 'source_network_id' :{'hex':'060d', 'name':'source_network_id', 'type':None, 'tech':'Generic'}, 'dest_network_id' :{'hex':'060e', 'name':'dest_network_id', 'type':None, 'tech':'Generic'}, 'source_node_id' :{'hex':'060f', 'name':'source_node_id', 'type':None, 'tech':'Generic'}, 'dest_node_id' :{'hex':'0610', 'name':'dest_node_id', 'type':None, 'tech':'Generic'}, 'dest_addr_np_resolution' :{'hex':'0611', 'name':'dest_addr_np_resolution', 'type':None, 'tech':'CDMA, TDMA (US Only)'}, 'dest_addr_np_information' :{'hex':'0612', 'name':'dest_addr_np_information', 'type':None, 'tech':'CDMA, TDMA (US Only)'}, 'dest_addr_np_country' :{'hex':'0613', 'name':'dest_addr_np_country', 'type':None, 'tech':'CDMA, TDMA (US Only)'}, 'PDC_MessageClass' :{'hex':'1101', 'name':'PDC_MessageClass', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 75 'PDC_PresentationOption' :{'hex':'1102', 'name':'PDC_PresentationOption', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 76 'PDC_AlertMechanism' :{'hex':'1103', 'name':'PDC_AlertMechanism', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 76 'PDC_Teleservice' :{'hex':'1104', 'name':'PDC_Teleservice', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 77 'PDC_MultiPartMessage' :{'hex':'1105', 'name':'PDC_MultiPartMessage', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 77 'PDC_PredefinedMsg' :{'hex':'1106', 'name':'PDC_PredefinedMsg', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 78 'display_time' :{'hex':'1201', 'name':'display_time', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.26, page 148 'sms_signal' :{'hex':'1203', 'name':'sms_signal', 'type':'integer', 'tech':'TDMA'}, # SMPP v3.4, section 5.3.2.40, page 158 'ms_validity' :{'hex':'1204', 'name':'ms_validity', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.27, page 149 'IS95A_AlertOnDelivery' :{'hex':'1304', 'name':'IS95A_AlertOnDelivery', 'type':None, 'tech':'CDMA'}, # v4 page 85 'IS95A_LanguageIndicator' :{'hex':'1306', 'name':'IS95A_LanguageIndicator', 'type':None, 'tech':'CDMA'}, # v4 page 86 'alert_on_message_delivery' :{'hex':'130c', 'name':'alert_on_message_delivery', 'type':None, 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.41, page 159 'its_reply_type' :{'hex':'1380', 'name':'its_reply_type', 'type':'integer', 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.42, page 159 'its_session_info' :{'hex':'1383', 'name':'its_session_info', 'type':'hex', 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.43, page 160 'operator_id' :{'hex':'1402', 'name':'operator_id', 'type':None, 'tech':'vendor extension'}, 'tariff' :{'hex':'1403', 'name':'tariff', 'type':None, 'tech':'Mobile Network Code vendor extension'}, 'mcc' :{'hex':'1450', 'name':'mcc', 'type':None, 'tech':'Mobile Country Code vendor extension'}, 'mnc' :{'hex':'1451', 'name':'mnc', 'type':None, 'tech':'Mobile Network Code vendor extension'} } def optional_parameter_tag_hex_by_name(n): return optional_parameter_tag_by_name.get(n,{}).get('hex') #### Decoding functions ####################################################### def unpack_pdu(pdu_bin): return decode_pdu(binascii.b2a_hex(pdu_bin)) def decode_pdu(pdu_hex): hex_ref = [pdu_hex] pdu = {} pdu['header'] = decode_header(hex_ref) command = pdu['header'].get('command_id', None) if command != None: body = decode_body(command, hex_ref) if len(body) > 0: pdu['body'] = body return pdu def decode_header(hex_ref): pdu_hex = hex_ref[0] header = {} (command_length, command_id, command_status, sequence_number, hex_ref[0]) = \ (pdu_hex[0:8], pdu_hex[8:16], pdu_hex[16:24], pdu_hex[24:32], pdu_hex[32: ]) length = int(command_length, 16) command = command_id_name_by_hex(command_id) status = command_status_name_by_hex(command_status) sequence = int(sequence_number, 16) header = {} header['command_length'] = length header['command_id'] = command header['command_status'] = status header['sequence_number'] = sequence return header def decode_body(command, hex_ref): body = {} if command != None: fields = mandatory_parameter_list_by_command_name(command) mandatory = decode_mandatory_parameters(fields, hex_ref) if len(mandatory) > 0: body['mandatory_parameters'] = mandatory optional = decode_optional_parameters(hex_ref) if len(optional) > 0: body['optional_parameters'] = optional return body def decode_mandatory_parameters(fields, hex_ref): mandatory_parameters = {} if len(hex_ref[0]) > 1: for field in fields: #old = len(hex_ref[0]) data = '' octet = '' count = 0 if field['var'] == True or field['var'] == False: while (len(hex_ref[0]) > 1 and (count < field['min'] or (field['var'] == True and count < field['max']+1 and octet != '00'))): octet = octpop(hex_ref) data += octet count += 1 elif field['type'] in ['string', 'xstring']: count = mandatory_parameters[field['var']] if count == 0: data = None else: for i in range(count): if len(hex_ref[0]) > 1: data += octpop(hex_ref) else: count = mandatory_parameters[field['var']] if field['map'] != None: mandatory_parameters[field['name']] = maps[field['map']+'_by_hex'].get(data, None) if field['map'] == None or mandatory_parameters[field['name']] == None: mandatory_parameters[field['name']] = decode_hex_type(data, field['type'], count, hex_ref) #print field['type'], (old - len(hex_ref[0]))/2, repr(data), field['name'], mandatory_parameters[field['name']] return mandatory_parameters def decode_optional_parameters(hex_ref): optional_parameters = [] hex = hex_ref[0] while len(hex) > 0: (tag_hex, length_hex, rest) = (hex[0:4], hex[4:8], hex[8: ]) tag = optional_parameter_tag_name_by_hex(tag_hex) if tag == None: tag = tag_hex length = int(length_hex, 16) (value_hex, tail) = (rest[0:length*2], rest[length*2: ]) if len(value_hex) == 0: value = None else: value = decode_hex_type(value_hex, optional_parameter_tag_type_by_hex(tag_hex)) hex = tail optional_parameters.append({'tag':tag, 'length':length, 'value':value}) return optional_parameters def decode_hex_type(hex, type, count=0, hex_ref=['']): if hex == None: return hex elif type == 'integer': return int(hex, 16) elif type == 'string': return re.sub('00','',hex).decode('hex') elif type == 'xstring': return hex.decode('hex') elif (type == 'dest_address' or type == 'unsuccess_sme'): list = [] fields = mandatory_parameter_list_by_command_name(type) for i in range(count): item = decode_mandatory_parameters(fields, hex_ref) if item.get('dest_flag', None) == 1: # 'dest_address' only subfields = mandatory_parameter_list_by_command_name('sme_dest_address') rest = decode_mandatory_parameters(subfields, hex_ref) item.update(rest) elif item.get('dest_flag', None) == 2: # 'dest_address' only subfields = mandatory_parameter_list_by_command_name('distribution_list') rest = decode_mandatory_parameters(subfields, hex_ref) item.update(rest) list.append(item) return list else: return hex def octpop(hex_ref): octet = None if len(hex_ref[0]) > 1: (octet, hex_ref[0]) = (hex_ref[0][0:2], hex_ref[0][2: ]) return octet #### Encoding functions ####################################################### def pack_pdu(pdu_obj): return binascii.a2b_hex(encode_pdu(pdu_obj)) def encode_pdu(pdu_obj): header = pdu_obj.get('header', {}) body = pdu_obj.get('body', {}) mandatory = body.get('mandatory_parameters', {}) optional = body.get('optional_parameters', []) body_hex = '' fields = mandatory_parameter_list_by_command_name(header['command_id']) body_hex += encode_mandatory_parameters(mandatory, fields) for opt in optional: body_hex += encode_optional_parameter(opt['tag'], opt['value']) actual_length = 16 + len(body_hex)/2 command_length = '%08x' % actual_length command_id = command_id_hex_by_name(header['command_id']) command_status = command_status_hex_by_name(header['command_status']) sequence_number = '%08x' % header['sequence_number'] pdu_hex = command_length + command_id + command_status + sequence_number + body_hex return pdu_hex def encode_mandatory_parameters(mandatory_obj, fields): mandatory_hex_array = [] index_names = {} index = 0 for field in fields: param = mandatory_obj.get(field['name'], None) param_length = None if param != None or field['min'] > 0: map = None if field['map'] != None: map = maps.get(field['map']+'_by_name', None) if isinstance(param, list): hex_list = [] for item in param: flagfields = mandatory_parameter_list_by_command_name(field['type']) plusfields = [] if item.get('dest_flag', None) == 1: plusfields = mandatory_parameter_list_by_command_name('sme_dest_address') elif item.get('dest_flag', None) == 2: plusfields = mandatory_parameter_list_by_command_name('distribution_list') hex_item = encode_mandatory_parameters(item, flagfields + plusfields) if isinstance(hex_item, str) and len(hex_item) > 0: hex_list.append(hex_item) param_length = len(hex_list) mandatory_hex_array.append(''.join(hex_list)) else: hex_param = encode_param_type( param, field['type'], field['min'], field['max'], map) param_length = len(hex_param)/2 mandatory_hex_array.append(hex_param) index_names[field['name']] = index length_index = index_names.get(field['var'], None) if length_index != None and param_length != None: mandatory_hex_array[length_index] = encode_param_type( param_length, 'integer', len(mandatory_hex_array[length_index])/2) index += 1 return ''.join(mandatory_hex_array) def encode_optional_parameter(tag, value): optional_hex_array = [] tag_hex = optional_parameter_tag_hex_by_name(tag) if tag_hex != None: value_hex = encode_param_type( value, optional_parameter_tag_type_by_hex(tag_hex)) length_hex = '%04x' % (len(value_hex)/2) optional_hex_array.append(tag_hex + length_hex + value_hex) return ''.join(optional_hex_array) def encode_param_type(param, type, min=0, max=None, map=None): if param == None: hex = None elif map != None: if type == 'integer' and isinstance(param, int): hex = ('%0'+str(min*2)+'x') % param else: hex = map.get(param, ('%0'+str(min*2)+'x') % 0) elif type == 'integer': hex = ('%0'+str(min*2)+'x') % int(param) elif type == 'string': hex = param.encode('hex') + '00' elif type == 'xstring': hex = param.encode('hex') elif type == 'bitmask': hex = param elif type == 'hex': hex = param else: hex = None - print type, min, max, repr(param), hex, map + if hex: + if len(hex) % 2: + # pad odd length hex strings + hex = '0' + hex + #print type, min, max, repr(param), hex, map return hex
dmaclay/python-smpp
90291a7dc0476b9c9f830232c15c1e85aceb7578
doesn't work for len(hex) = 3
diff --git a/smpp/pdu.py b/smpp/pdu.py index e6a2e25..650b1d1 100644 --- a/smpp/pdu.py +++ b/smpp/pdu.py @@ -507,541 +507,536 @@ maps['esm_class_bits'] = { 'feature_mask' :'c0', 'mode_default' :'00', 'mode_datagram' :'01', 'mode_forward' :'02', 'mode_store_and_forward' :'03', 'type_default' :'00', 'type_delivery_receipt' :'04', 'type_delivery_ack' :'08', 'type_0011' :'0a', 'type_user_ack' :'10', 'type_0101' :'14', 'type_conversation_abort' :'18', 'type_0111' :'1a', 'type_intermed_deliv_notif' :'20', 'type_1001' :'24', 'type_1010' :'28', 'type_1011' :'2a', 'type_1100' :'30', 'type_1101' :'34', 'type_1110' :'38', 'type_1111' :'3a', 'feature_none' :'00', 'feature_UDHI' :'40', 'feature_reply_path' :'80', 'feature_UDHI_and_reply_path':'c0' } # Registered Delivery bits - SMPP v3.4, section 5.2.17, page 124 maps['registered_delivery_bits'] = { 'receipt_mask' :'03', 'ack_mask' :'0c', 'intermed_notif_mask' :'80', 'receipt_none' :'00', 'receipt_always' :'01', 'receipt_on_fail' :'02', 'receipt_res' :'03', 'ack_none' :'00', 'ack_delivery' :'04', 'ack_user' :'08', 'ack_delivery_and_user':'0c', 'intermed_notif_none' :'00', 'intermed_notif' :'10' } # submit_multi dest_flag constants - SMPP v3.4, section 5.2.25, page 129 #maps['dest_flag_by_name'] = { #'SME Address' :1, #'Distribution List Name':2 #} # Message State codes returned in query_sm_resp PDUs - SMPP v3.4, section 5.2.28, table 5-6, page 130 maps['message_state_by_name'] = { 'ENROUTE' :1, 'DELIVERED' :2, 'EXPIRED' :3, 'DELETED' :4, 'UNDELIVERABLE':5, 'ACCEPTED' :6, 'UNKNOWN' :7, 'REJECTED' :8 } # Facility Code bits for SMPP v4 maps['facility_code_bits'] = { 'GF_PVCY' :'00000001', 'GF_SUBADDR':'00000002', 'NF_CC' :'00080000', 'NF_PDC' :'00010000', 'NF_IS136' :'00020000', 'NF_IS95A' :'00040000' } # Optional Parameter Tags - SMPP v3.4, section 5.3.2, Table 5-7, page 132-133 optional_parameter_tag_by_hex = { '0005':{'hex':'0005', 'name':'dest_addr_subunit', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.1, page 134 '0006':{'hex':'0006', 'name':'dest_network_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.3, page 135 '0007':{'hex':'0007', 'name':'dest_bearer_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.5, page 136 '0008':{'hex':'0008', 'name':'dest_telematics_id', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.7, page 137 '000d':{'hex':'000d', 'name':'source_addr_subunit', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.2, page 134 '000e':{'hex':'000e', 'name':'source_network_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.4, page 135 '000f':{'hex':'000f', 'name':'source_bearer_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.6, page 136 '0010':{'hex':'0010', 'name':'source_telematics_id', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.8, page 137 '0017':{'hex':'0017', 'name':'qos_time_to_live', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.9, page 138 '0019':{'hex':'0019', 'name':'payload_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.10, page 138 '001d':{'hex':'001d', 'name':'additional_status_info_text', 'type':'string', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.11, page 139 '001e':{'hex':'001e', 'name':'receipted_message_id', 'type':'string', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.12, page 139 '0030':{'hex':'0030', 'name':'ms_msg_wait_facilities', 'type':'bitmask', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.13, page 140 '0101':{'hex':'0101', 'name':'PVCY_AuthenticationStr', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 58-62 '0201':{'hex':'0201', 'name':'privacy_indicator', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.14, page 141 '0202':{'hex':'0202', 'name':'source_subaddress', 'type':'hex', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.15, page 142 '0203':{'hex':'0203', 'name':'dest_subaddress', 'type':'hex', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.16, page 143 '0204':{'hex':'0204', 'name':'user_message_reference', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.17, page 143 '0205':{'hex':'0205', 'name':'user_response_code', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.18, page 144 '020a':{'hex':'020a', 'name':'source_port', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.20, page 145 '020b':{'hex':'020b', 'name':'destination_port', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.21, page 145 '020c':{'hex':'020c', 'name':'sar_msg_ref_num', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.22, page 146 '020d':{'hex':'020d', 'name':'language_indicator', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.19, page 144 '020e':{'hex':'020e', 'name':'sar_total_segments', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.23, page 147 '020f':{'hex':'020f', 'name':'sar_segment_seqnum', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.24, page 147 '0210':{'hex':'0210', 'name':'sc_interface_version', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.25, page 148 '0301':{'hex':'0301', 'name':'CC_CBN', 'type':None, 'tech':'V4'}, # v4 page 70 '0302':{'hex':'0302', 'name':'callback_num_pres_ind', 'type':'bitmask', 'tech':'TDMA'}, # SMPP v3.4, section 5.3.2.37, page 156 '0303':{'hex':'0303', 'name':'callback_num_atag', 'type':'hex', 'tech':'TDMA'}, # SMPP v3.4, section 5.3.2.38, page 157 '0304':{'hex':'0304', 'name':'number_of_messages', 'type':'integer', 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.39, page 158 '0381':{'hex':'0381', 'name':'callback_num', 'type':'hex', 'tech':'CDMA, TDMA, GSM, iDEN'}, # SMPP v3.4, section 5.3.2.36, page 155 '0420':{'hex':'0420', 'name':'dpf_result', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.28, page 149 '0421':{'hex':'0421', 'name':'set_dpf', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.29, page 150 '0422':{'hex':'0422', 'name':'ms_availability_status', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.30, page 151 '0423':{'hex':'0423', 'name':'network_error_code', 'type':'hex', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.31, page 152 '0424':{'hex':'0424', 'name':'message_payload', 'type':'hex', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.32, page 153 '0425':{'hex':'0425', 'name':'delivery_failure_reason', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.33, page 153 '0426':{'hex':'0426', 'name':'more_messages_to_send', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.34, page 154 '0427':{'hex':'0427', 'name':'message_state', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.35, page 154 '0428':{'hex':'0428', 'name':'congestion_state', 'type':None, 'tech':'Generic'}, '0501':{'hex':'0501', 'name':'ussd_service_op', 'type':'hex', 'tech':'GSM (USSD)'}, # SMPP v3.4, section 5.3.2.44, page 161 '0600':{'hex':'0600', 'name':'broadcast_channel_indicator', 'type':None, 'tech':'GSM'}, '0601':{'hex':'0601', 'name':'broadcast_content_type', 'type':None, 'tech':'CDMA, TDMA, GSM'}, '0602':{'hex':'0602', 'name':'broadcast_content_type_info', 'type':None, 'tech':'CDMA, TDMA'}, '0603':{'hex':'0603', 'name':'broadcast_message_class', 'type':None, 'tech':'GSM'}, '0604':{'hex':'0604', 'name':'broadcast_rep_num', 'type':None, 'tech':'GSM'}, '0605':{'hex':'0605', 'name':'broadcast_frequency_interval', 'type':None, 'tech':'CDMA, TDMA, GSM'}, '0606':{'hex':'0606', 'name':'broadcast_area_identifier', 'type':None, 'tech':'CDMA, TDMA, GSM'}, '0607':{'hex':'0607', 'name':'broadcast_error_status', 'type':None, 'tech':'CDMA, TDMA, GSM'}, '0608':{'hex':'0608', 'name':'broadcast_area_success', 'type':None, 'tech':'GSM'}, '0609':{'hex':'0609', 'name':'broadcast_end_time', 'type':None, 'tech':'CDMA, TDMA, GSM'}, '060a':{'hex':'060a', 'name':'broadcast_service_group', 'type':None, 'tech':'CDMA, TDMA'}, '060b':{'hex':'060b', 'name':'billing_identification', 'type':None, 'tech':'Generic'}, '060d':{'hex':'060d', 'name':'source_network_id', 'type':None, 'tech':'Generic'}, '060e':{'hex':'060e', 'name':'dest_network_id', 'type':None, 'tech':'Generic'}, '060f':{'hex':'060f', 'name':'source_node_id', 'type':None, 'tech':'Generic'}, '0610':{'hex':'0610', 'name':'dest_node_id', 'type':None, 'tech':'Generic'}, '0611':{'hex':'0611', 'name':'dest_addr_np_resolution', 'type':None, 'tech':'CDMA, TDMA (US Only)'}, '0612':{'hex':'0612', 'name':'dest_addr_np_information', 'type':None, 'tech':'CDMA, TDMA (US Only)'}, '0613':{'hex':'0613', 'name':'dest_addr_np_country', 'type':None, 'tech':'CDMA, TDMA (US Only)'}, '1101':{'hex':'1101', 'name':'PDC_MessageClass', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 75 '1102':{'hex':'1102', 'name':'PDC_PresentationOption', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 76 '1103':{'hex':'1103', 'name':'PDC_AlertMechanism', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 76 '1104':{'hex':'1104', 'name':'PDC_Teleservice', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 77 '1105':{'hex':'1105', 'name':'PDC_MultiPartMessage', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 77 '1106':{'hex':'1106', 'name':'PDC_PredefinedMsg', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 78 '1201':{'hex':'1201', 'name':'display_time', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.26, page 148 '1203':{'hex':'1203', 'name':'sms_signal', 'type':'integer', 'tech':'TDMA'}, # SMPP v3.4, section 5.3.2.40, page 158 '1204':{'hex':'1204', 'name':'ms_validity', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.27, page 149 '1304':{'hex':'1304', 'name':'IS95A_AlertOnDelivery', 'type':None, 'tech':'CDMA'}, # v4 page 85 '1306':{'hex':'1306', 'name':'IS95A_LanguageIndicator', 'type':None, 'tech':'CDMA'}, # v4 page 86 '130c':{'hex':'130c', 'name':'alert_on_message_delivery', 'type':None, 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.41, page 159 '1380':{'hex':'1380', 'name':'its_reply_type', 'type':'integer', 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.42, page 159 '1383':{'hex':'1383', 'name':'its_session_info', 'type':'hex', 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.43, page 160 '1402':{'hex':'1402', 'name':'operator_id', 'type':None, 'tech':'vendor extension'}, '1403':{'hex':'1403', 'name':'tariff', 'type':None, 'tech':'Mobile Network Code vendor extension'}, '1450':{'hex':'1450', 'name':'mcc', 'type':None, 'tech':'Mobile Country Code vendor extension'}, '1451':{'hex':'1451', 'name':'mnc', 'type':None, 'tech':'Mobile Network Code vendor extension'} } def optional_parameter_tag_name_by_hex(x): return optional_parameter_tag_by_hex.get(x,{}).get('name') def optional_parameter_tag_type_by_hex(x): return optional_parameter_tag_by_hex.get(x,{}).get('type') optional_parameter_tag_by_name = { 'dest_addr_subunit' :{'hex':'0005', 'name':'dest_addr_subunit', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.1, page 134 'dest_network_type' :{'hex':'0006', 'name':'dest_network_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.3, page 135 'dest_bearer_type' :{'hex':'0007', 'name':'dest_bearer_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.5, page 136 'dest_telematics_id' :{'hex':'0008', 'name':'dest_telematics_id', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.7, page 137 'source_addr_subunit' :{'hex':'000d', 'name':'source_addr_subunit', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.2, page 134 'source_network_type' :{'hex':'000e', 'name':'source_network_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.4, page 135 'source_bearer_type' :{'hex':'000f', 'name':'source_bearer_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.6, page 136 'source_telematics_id' :{'hex':'0010', 'name':'source_telematics_id', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.8, page 137 'qos_time_to_live' :{'hex':'0017', 'name':'qos_time_to_live', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.9, page 138 'payload_type' :{'hex':'0019', 'name':'payload_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.10, page 138 'additional_status_info_text' :{'hex':'001d', 'name':'additional_status_info_text', 'type':'string', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.11, page 139 'receipted_message_id' :{'hex':'001e', 'name':'receipted_message_id', 'type':'string', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.12, page 139 'ms_msg_wait_facilities' :{'hex':'0030', 'name':'ms_msg_wait_facilities', 'type':'bitmask', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.13, page 140 'PVCY_AuthenticationStr' :{'hex':'0101', 'name':'PVCY_AuthenticationStr', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 58-62 'privacy_indicator' :{'hex':'0201', 'name':'privacy_indicator', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.14, page 141 'source_subaddress' :{'hex':'0202', 'name':'source_subaddress', 'type':'hex', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.15, page 142 'dest_subaddress' :{'hex':'0203', 'name':'dest_subaddress', 'type':'hex', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.16, page 143 'user_message_reference' :{'hex':'0204', 'name':'user_message_reference', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.17, page 143 'user_response_code' :{'hex':'0205', 'name':'user_response_code', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.18, page 144 'source_port' :{'hex':'020a', 'name':'source_port', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.20, page 145 'destination_port' :{'hex':'020b', 'name':'destination_port', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.21, page 145 'sar_msg_ref_num' :{'hex':'020c', 'name':'sar_msg_ref_num', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.22, page 146 'language_indicator' :{'hex':'020d', 'name':'language_indicator', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.19, page 144 'sar_total_segments' :{'hex':'020e', 'name':'sar_total_segments', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.23, page 147 'sar_segment_seqnum' :{'hex':'020f', 'name':'sar_segment_seqnum', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.24, page 147 'sc_interface_version' :{'hex':'0210', 'name':'sc_interface_version', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.25, page 148 'CC_CBN' :{'hex':'0301', 'name':'CC_CBN', 'type':None, 'tech':'V4'}, # v4 page 70 'callback_num_pres_ind' :{'hex':'0302', 'name':'callback_num_pres_ind', 'type':'bitmask', 'tech':'TDMA'}, # SMPP v3.4, section 5.3.2.37, page 156 'callback_num_atag' :{'hex':'0303', 'name':'callback_num_atag', 'type':'hex', 'tech':'TDMA'}, # SMPP v3.4, section 5.3.2.38, page 157 'number_of_messages' :{'hex':'0304', 'name':'number_of_messages', 'type':'integer', 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.39, page 158 'callback_num' :{'hex':'0381', 'name':'callback_num', 'type':'hex', 'tech':'CDMA, TDMA, GSM, iDEN'}, # SMPP v3.4, section 5.3.2.36, page 155 'dpf_result' :{'hex':'0420', 'name':'dpf_result', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.28, page 149 'set_dpf' :{'hex':'0421', 'name':'set_dpf', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.29, page 150 'ms_availability_status' :{'hex':'0422', 'name':'ms_availability_status', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.30, page 151 'network_error_code' :{'hex':'0423', 'name':'network_error_code', 'type':'hex', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.31, page 152 'message_payload' :{'hex':'0424', 'name':'message_payload', 'type':'hex', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.32, page 153 'delivery_failure_reason' :{'hex':'0425', 'name':'delivery_failure_reason', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.33, page 153 'more_messages_to_send' :{'hex':'0426', 'name':'more_messages_to_send', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.34, page 154 'message_state' :{'hex':'0427', 'name':'message_state', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.35, page 154 'congestion_state' :{'hex':'0428', 'name':'congestion_state', 'type':None, 'tech':'Generic'}, 'ussd_service_op' :{'hex':'0501', 'name':'ussd_service_op', 'type':'hex', 'tech':'GSM (USSD)'}, # SMPP v3.4, section 5.3.2.44, page 161 'broadcast_channel_indicator' :{'hex':'0600', 'name':'broadcast_channel_indicator', 'type':None, 'tech':'GSM'}, 'broadcast_content_type' :{'hex':'0601', 'name':'broadcast_content_type', 'type':None, 'tech':'CDMA, TDMA, GSM'}, 'broadcast_content_type_info' :{'hex':'0602', 'name':'broadcast_content_type_info', 'type':None, 'tech':'CDMA, TDMA'}, 'broadcast_message_class' :{'hex':'0603', 'name':'broadcast_message_class', 'type':None, 'tech':'GSM'}, 'broadcast_rep_num' :{'hex':'0604', 'name':'broadcast_rep_num', 'type':None, 'tech':'GSM'}, 'broadcast_frequency_interval':{'hex':'0605', 'name':'broadcast_frequency_interval', 'type':None, 'tech':'CDMA, TDMA, GSM'}, 'broadcast_area_identifier' :{'hex':'0606', 'name':'broadcast_area_identifier', 'type':None, 'tech':'CDMA, TDMA, GSM'}, 'broadcast_error_status' :{'hex':'0607', 'name':'broadcast_error_status', 'type':None, 'tech':'CDMA, TDMA, GSM'}, 'broadcast_area_success' :{'hex':'0608', 'name':'broadcast_area_success', 'type':None, 'tech':'GSM'}, 'broadcast_end_time' :{'hex':'0609', 'name':'broadcast_end_time', 'type':None, 'tech':'CDMA, TDMA, GSM'}, 'broadcast_service_group' :{'hex':'060a', 'name':'broadcast_service_group', 'type':None, 'tech':'CDMA, TDMA'}, 'billing_identification' :{'hex':'060b', 'name':'billing_identification', 'type':None, 'tech':'Generic'}, 'source_network_id' :{'hex':'060d', 'name':'source_network_id', 'type':None, 'tech':'Generic'}, 'dest_network_id' :{'hex':'060e', 'name':'dest_network_id', 'type':None, 'tech':'Generic'}, 'source_node_id' :{'hex':'060f', 'name':'source_node_id', 'type':None, 'tech':'Generic'}, 'dest_node_id' :{'hex':'0610', 'name':'dest_node_id', 'type':None, 'tech':'Generic'}, 'dest_addr_np_resolution' :{'hex':'0611', 'name':'dest_addr_np_resolution', 'type':None, 'tech':'CDMA, TDMA (US Only)'}, 'dest_addr_np_information' :{'hex':'0612', 'name':'dest_addr_np_information', 'type':None, 'tech':'CDMA, TDMA (US Only)'}, 'dest_addr_np_country' :{'hex':'0613', 'name':'dest_addr_np_country', 'type':None, 'tech':'CDMA, TDMA (US Only)'}, 'PDC_MessageClass' :{'hex':'1101', 'name':'PDC_MessageClass', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 75 'PDC_PresentationOption' :{'hex':'1102', 'name':'PDC_PresentationOption', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 76 'PDC_AlertMechanism' :{'hex':'1103', 'name':'PDC_AlertMechanism', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 76 'PDC_Teleservice' :{'hex':'1104', 'name':'PDC_Teleservice', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 77 'PDC_MultiPartMessage' :{'hex':'1105', 'name':'PDC_MultiPartMessage', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 77 'PDC_PredefinedMsg' :{'hex':'1106', 'name':'PDC_PredefinedMsg', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 78 'display_time' :{'hex':'1201', 'name':'display_time', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.26, page 148 'sms_signal' :{'hex':'1203', 'name':'sms_signal', 'type':'integer', 'tech':'TDMA'}, # SMPP v3.4, section 5.3.2.40, page 158 'ms_validity' :{'hex':'1204', 'name':'ms_validity', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.27, page 149 'IS95A_AlertOnDelivery' :{'hex':'1304', 'name':'IS95A_AlertOnDelivery', 'type':None, 'tech':'CDMA'}, # v4 page 85 'IS95A_LanguageIndicator' :{'hex':'1306', 'name':'IS95A_LanguageIndicator', 'type':None, 'tech':'CDMA'}, # v4 page 86 'alert_on_message_delivery' :{'hex':'130c', 'name':'alert_on_message_delivery', 'type':None, 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.41, page 159 'its_reply_type' :{'hex':'1380', 'name':'its_reply_type', 'type':'integer', 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.42, page 159 'its_session_info' :{'hex':'1383', 'name':'its_session_info', 'type':'hex', 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.43, page 160 'operator_id' :{'hex':'1402', 'name':'operator_id', 'type':None, 'tech':'vendor extension'}, 'tariff' :{'hex':'1403', 'name':'tariff', 'type':None, 'tech':'Mobile Network Code vendor extension'}, 'mcc' :{'hex':'1450', 'name':'mcc', 'type':None, 'tech':'Mobile Country Code vendor extension'}, 'mnc' :{'hex':'1451', 'name':'mnc', 'type':None, 'tech':'Mobile Network Code vendor extension'} } def optional_parameter_tag_hex_by_name(n): return optional_parameter_tag_by_name.get(n,{}).get('hex') #### Decoding functions ####################################################### def unpack_pdu(pdu_bin): return decode_pdu(binascii.b2a_hex(pdu_bin)) def decode_pdu(pdu_hex): hex_ref = [pdu_hex] pdu = {} pdu['header'] = decode_header(hex_ref) command = pdu['header'].get('command_id', None) if command != None: body = decode_body(command, hex_ref) if len(body) > 0: pdu['body'] = body return pdu def decode_header(hex_ref): pdu_hex = hex_ref[0] header = {} (command_length, command_id, command_status, sequence_number, hex_ref[0]) = \ (pdu_hex[0:8], pdu_hex[8:16], pdu_hex[16:24], pdu_hex[24:32], pdu_hex[32: ]) length = int(command_length, 16) command = command_id_name_by_hex(command_id) status = command_status_name_by_hex(command_status) sequence = int(sequence_number, 16) header = {} header['command_length'] = length header['command_id'] = command header['command_status'] = status header['sequence_number'] = sequence return header def decode_body(command, hex_ref): body = {} if command != None: fields = mandatory_parameter_list_by_command_name(command) mandatory = decode_mandatory_parameters(fields, hex_ref) if len(mandatory) > 0: body['mandatory_parameters'] = mandatory optional = decode_optional_parameters(hex_ref) if len(optional) > 0: body['optional_parameters'] = optional return body def decode_mandatory_parameters(fields, hex_ref): mandatory_parameters = {} if len(hex_ref[0]) > 1: for field in fields: #old = len(hex_ref[0]) data = '' octet = '' count = 0 if field['var'] == True or field['var'] == False: while (len(hex_ref[0]) > 1 and (count < field['min'] or (field['var'] == True and count < field['max']+1 and octet != '00'))): octet = octpop(hex_ref) data += octet count += 1 elif field['type'] in ['string', 'xstring']: count = mandatory_parameters[field['var']] if count == 0: data = None else: for i in range(count): if len(hex_ref[0]) > 1: data += octpop(hex_ref) else: count = mandatory_parameters[field['var']] if field['map'] != None: mandatory_parameters[field['name']] = maps[field['map']+'_by_hex'].get(data, None) if field['map'] == None or mandatory_parameters[field['name']] == None: mandatory_parameters[field['name']] = decode_hex_type(data, field['type'], count, hex_ref) #print field['type'], (old - len(hex_ref[0]))/2, repr(data), field['name'], mandatory_parameters[field['name']] return mandatory_parameters def decode_optional_parameters(hex_ref): optional_parameters = [] hex = hex_ref[0] while len(hex) > 0: (tag_hex, length_hex, rest) = (hex[0:4], hex[4:8], hex[8: ]) tag = optional_parameter_tag_name_by_hex(tag_hex) if tag == None: tag = tag_hex length = int(length_hex, 16) (value_hex, tail) = (rest[0:length*2], rest[length*2: ]) if len(value_hex) == 0: value = None else: value = decode_hex_type(value_hex, optional_parameter_tag_type_by_hex(tag_hex)) hex = tail optional_parameters.append({'tag':tag, 'length':length, 'value':value}) return optional_parameters def decode_hex_type(hex, type, count=0, hex_ref=['']): if hex == None: return hex elif type == 'integer': return int(hex, 16) elif type == 'string': return re.sub('00','',hex).decode('hex') elif type == 'xstring': return hex.decode('hex') elif (type == 'dest_address' or type == 'unsuccess_sme'): list = [] fields = mandatory_parameter_list_by_command_name(type) for i in range(count): item = decode_mandatory_parameters(fields, hex_ref) if item.get('dest_flag', None) == 1: # 'dest_address' only subfields = mandatory_parameter_list_by_command_name('sme_dest_address') rest = decode_mandatory_parameters(subfields, hex_ref) item.update(rest) elif item.get('dest_flag', None) == 2: # 'dest_address' only subfields = mandatory_parameter_list_by_command_name('distribution_list') rest = decode_mandatory_parameters(subfields, hex_ref) item.update(rest) list.append(item) return list else: return hex def octpop(hex_ref): octet = None if len(hex_ref[0]) > 1: (octet, hex_ref[0]) = (hex_ref[0][0:2], hex_ref[0][2: ]) return octet #### Encoding functions ####################################################### def pack_pdu(pdu_obj): return binascii.a2b_hex(encode_pdu(pdu_obj)) def encode_pdu(pdu_obj): header = pdu_obj.get('header', {}) body = pdu_obj.get('body', {}) mandatory = body.get('mandatory_parameters', {}) optional = body.get('optional_parameters', []) body_hex = '' fields = mandatory_parameter_list_by_command_name(header['command_id']) body_hex += encode_mandatory_parameters(mandatory, fields) for opt in optional: body_hex += encode_optional_parameter(opt['tag'], opt['value']) actual_length = 16 + len(body_hex)/2 command_length = '%08x' % actual_length command_id = command_id_hex_by_name(header['command_id']) command_status = command_status_hex_by_name(header['command_status']) sequence_number = '%08x' % header['sequence_number'] pdu_hex = command_length + command_id + command_status + sequence_number + body_hex return pdu_hex def encode_mandatory_parameters(mandatory_obj, fields): mandatory_hex_array = [] index_names = {} index = 0 for field in fields: param = mandatory_obj.get(field['name'], None) param_length = None if param != None or field['min'] > 0: map = None if field['map'] != None: map = maps.get(field['map']+'_by_name', None) if isinstance(param, list): hex_list = [] for item in param: flagfields = mandatory_parameter_list_by_command_name(field['type']) plusfields = [] if item.get('dest_flag', None) == 1: plusfields = mandatory_parameter_list_by_command_name('sme_dest_address') elif item.get('dest_flag', None) == 2: plusfields = mandatory_parameter_list_by_command_name('distribution_list') hex_item = encode_mandatory_parameters(item, flagfields + plusfields) if isinstance(hex_item, str) and len(hex_item) > 0: hex_list.append(hex_item) param_length = len(hex_list) mandatory_hex_array.append(''.join(hex_list)) else: hex_param = encode_param_type( param, field['type'], field['min'], field['max'], map) param_length = len(hex_param)/2 mandatory_hex_array.append(hex_param) index_names[field['name']] = index length_index = index_names.get(field['var'], None) if length_index != None and param_length != None: mandatory_hex_array[length_index] = encode_param_type( param_length, 'integer', len(mandatory_hex_array[length_index])/2) index += 1 return ''.join(mandatory_hex_array) def encode_optional_parameter(tag, value): optional_hex_array = [] tag_hex = optional_parameter_tag_hex_by_name(tag) if tag_hex != None: value_hex = encode_param_type( value, optional_parameter_tag_type_by_hex(tag_hex)) length_hex = '%04x' % (len(value_hex)/2) optional_hex_array.append(tag_hex + length_hex + value_hex) return ''.join(optional_hex_array) -def encode_param_type(param, type, min=1, max=None, map=None): +def encode_param_type(param, type, min=0, max=None, map=None): if param == None: hex = None elif map != None: if type == 'integer' and isinstance(param, int): hex = ('%0'+str(min*2)+'x') % param else: hex = map.get(param, ('%0'+str(min*2)+'x') % 0) elif type == 'integer': hex = ('%0'+str(min*2)+'x') % int(param) - print "HEX: ",hex elif type == 'string': hex = param.encode('hex') + '00' elif type == 'xstring': hex = param.encode('hex') elif type == 'bitmask': hex = param elif type == 'hex': hex = param else: hex = None - #if hex == None: - #hex = '' - #if min > 0: - #hex = ('%0'+str(min*2)+'x') % 0 - #print type, min, max, repr(param), hex, map + print type, min, max, repr(param), hex, map return hex
dmaclay/python-smpp
062638b1bb8fd9dec1056e8832dcd953aed7fe56
dumb idea
diff --git a/smpp/pdu.py b/smpp/pdu.py index d4fdc42..e6a2e25 100644 --- a/smpp/pdu.py +++ b/smpp/pdu.py @@ -507,541 +507,541 @@ maps['esm_class_bits'] = { 'feature_mask' :'c0', 'mode_default' :'00', 'mode_datagram' :'01', 'mode_forward' :'02', 'mode_store_and_forward' :'03', 'type_default' :'00', 'type_delivery_receipt' :'04', 'type_delivery_ack' :'08', 'type_0011' :'0a', 'type_user_ack' :'10', 'type_0101' :'14', 'type_conversation_abort' :'18', 'type_0111' :'1a', 'type_intermed_deliv_notif' :'20', 'type_1001' :'24', 'type_1010' :'28', 'type_1011' :'2a', 'type_1100' :'30', 'type_1101' :'34', 'type_1110' :'38', 'type_1111' :'3a', 'feature_none' :'00', 'feature_UDHI' :'40', 'feature_reply_path' :'80', 'feature_UDHI_and_reply_path':'c0' } # Registered Delivery bits - SMPP v3.4, section 5.2.17, page 124 maps['registered_delivery_bits'] = { 'receipt_mask' :'03', 'ack_mask' :'0c', 'intermed_notif_mask' :'80', 'receipt_none' :'00', 'receipt_always' :'01', 'receipt_on_fail' :'02', 'receipt_res' :'03', 'ack_none' :'00', 'ack_delivery' :'04', 'ack_user' :'08', 'ack_delivery_and_user':'0c', 'intermed_notif_none' :'00', 'intermed_notif' :'10' } # submit_multi dest_flag constants - SMPP v3.4, section 5.2.25, page 129 #maps['dest_flag_by_name'] = { #'SME Address' :1, #'Distribution List Name':2 #} # Message State codes returned in query_sm_resp PDUs - SMPP v3.4, section 5.2.28, table 5-6, page 130 maps['message_state_by_name'] = { 'ENROUTE' :1, 'DELIVERED' :2, 'EXPIRED' :3, 'DELETED' :4, 'UNDELIVERABLE':5, 'ACCEPTED' :6, 'UNKNOWN' :7, 'REJECTED' :8 } # Facility Code bits for SMPP v4 maps['facility_code_bits'] = { 'GF_PVCY' :'00000001', 'GF_SUBADDR':'00000002', 'NF_CC' :'00080000', 'NF_PDC' :'00010000', 'NF_IS136' :'00020000', 'NF_IS95A' :'00040000' } # Optional Parameter Tags - SMPP v3.4, section 5.3.2, Table 5-7, page 132-133 optional_parameter_tag_by_hex = { '0005':{'hex':'0005', 'name':'dest_addr_subunit', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.1, page 134 '0006':{'hex':'0006', 'name':'dest_network_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.3, page 135 '0007':{'hex':'0007', 'name':'dest_bearer_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.5, page 136 '0008':{'hex':'0008', 'name':'dest_telematics_id', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.7, page 137 '000d':{'hex':'000d', 'name':'source_addr_subunit', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.2, page 134 '000e':{'hex':'000e', 'name':'source_network_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.4, page 135 '000f':{'hex':'000f', 'name':'source_bearer_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.6, page 136 '0010':{'hex':'0010', 'name':'source_telematics_id', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.8, page 137 '0017':{'hex':'0017', 'name':'qos_time_to_live', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.9, page 138 '0019':{'hex':'0019', 'name':'payload_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.10, page 138 '001d':{'hex':'001d', 'name':'additional_status_info_text', 'type':'string', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.11, page 139 '001e':{'hex':'001e', 'name':'receipted_message_id', 'type':'string', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.12, page 139 '0030':{'hex':'0030', 'name':'ms_msg_wait_facilities', 'type':'bitmask', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.13, page 140 '0101':{'hex':'0101', 'name':'PVCY_AuthenticationStr', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 58-62 '0201':{'hex':'0201', 'name':'privacy_indicator', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.14, page 141 '0202':{'hex':'0202', 'name':'source_subaddress', 'type':'hex', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.15, page 142 '0203':{'hex':'0203', 'name':'dest_subaddress', 'type':'hex', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.16, page 143 '0204':{'hex':'0204', 'name':'user_message_reference', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.17, page 143 '0205':{'hex':'0205', 'name':'user_response_code', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.18, page 144 '020a':{'hex':'020a', 'name':'source_port', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.20, page 145 '020b':{'hex':'020b', 'name':'destination_port', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.21, page 145 '020c':{'hex':'020c', 'name':'sar_msg_ref_num', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.22, page 146 '020d':{'hex':'020d', 'name':'language_indicator', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.19, page 144 '020e':{'hex':'020e', 'name':'sar_total_segments', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.23, page 147 '020f':{'hex':'020f', 'name':'sar_segment_seqnum', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.24, page 147 '0210':{'hex':'0210', 'name':'sc_interface_version', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.25, page 148 '0301':{'hex':'0301', 'name':'CC_CBN', 'type':None, 'tech':'V4'}, # v4 page 70 '0302':{'hex':'0302', 'name':'callback_num_pres_ind', 'type':'bitmask', 'tech':'TDMA'}, # SMPP v3.4, section 5.3.2.37, page 156 '0303':{'hex':'0303', 'name':'callback_num_atag', 'type':'hex', 'tech':'TDMA'}, # SMPP v3.4, section 5.3.2.38, page 157 '0304':{'hex':'0304', 'name':'number_of_messages', 'type':'integer', 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.39, page 158 '0381':{'hex':'0381', 'name':'callback_num', 'type':'hex', 'tech':'CDMA, TDMA, GSM, iDEN'}, # SMPP v3.4, section 5.3.2.36, page 155 '0420':{'hex':'0420', 'name':'dpf_result', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.28, page 149 '0421':{'hex':'0421', 'name':'set_dpf', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.29, page 150 '0422':{'hex':'0422', 'name':'ms_availability_status', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.30, page 151 '0423':{'hex':'0423', 'name':'network_error_code', 'type':'hex', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.31, page 152 '0424':{'hex':'0424', 'name':'message_payload', 'type':'hex', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.32, page 153 '0425':{'hex':'0425', 'name':'delivery_failure_reason', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.33, page 153 '0426':{'hex':'0426', 'name':'more_messages_to_send', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.34, page 154 '0427':{'hex':'0427', 'name':'message_state', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.35, page 154 '0428':{'hex':'0428', 'name':'congestion_state', 'type':None, 'tech':'Generic'}, '0501':{'hex':'0501', 'name':'ussd_service_op', 'type':'hex', 'tech':'GSM (USSD)'}, # SMPP v3.4, section 5.3.2.44, page 161 '0600':{'hex':'0600', 'name':'broadcast_channel_indicator', 'type':None, 'tech':'GSM'}, '0601':{'hex':'0601', 'name':'broadcast_content_type', 'type':None, 'tech':'CDMA, TDMA, GSM'}, '0602':{'hex':'0602', 'name':'broadcast_content_type_info', 'type':None, 'tech':'CDMA, TDMA'}, '0603':{'hex':'0603', 'name':'broadcast_message_class', 'type':None, 'tech':'GSM'}, '0604':{'hex':'0604', 'name':'broadcast_rep_num', 'type':None, 'tech':'GSM'}, '0605':{'hex':'0605', 'name':'broadcast_frequency_interval', 'type':None, 'tech':'CDMA, TDMA, GSM'}, '0606':{'hex':'0606', 'name':'broadcast_area_identifier', 'type':None, 'tech':'CDMA, TDMA, GSM'}, '0607':{'hex':'0607', 'name':'broadcast_error_status', 'type':None, 'tech':'CDMA, TDMA, GSM'}, '0608':{'hex':'0608', 'name':'broadcast_area_success', 'type':None, 'tech':'GSM'}, '0609':{'hex':'0609', 'name':'broadcast_end_time', 'type':None, 'tech':'CDMA, TDMA, GSM'}, '060a':{'hex':'060a', 'name':'broadcast_service_group', 'type':None, 'tech':'CDMA, TDMA'}, '060b':{'hex':'060b', 'name':'billing_identification', 'type':None, 'tech':'Generic'}, '060d':{'hex':'060d', 'name':'source_network_id', 'type':None, 'tech':'Generic'}, '060e':{'hex':'060e', 'name':'dest_network_id', 'type':None, 'tech':'Generic'}, '060f':{'hex':'060f', 'name':'source_node_id', 'type':None, 'tech':'Generic'}, '0610':{'hex':'0610', 'name':'dest_node_id', 'type':None, 'tech':'Generic'}, '0611':{'hex':'0611', 'name':'dest_addr_np_resolution', 'type':None, 'tech':'CDMA, TDMA (US Only)'}, '0612':{'hex':'0612', 'name':'dest_addr_np_information', 'type':None, 'tech':'CDMA, TDMA (US Only)'}, '0613':{'hex':'0613', 'name':'dest_addr_np_country', 'type':None, 'tech':'CDMA, TDMA (US Only)'}, '1101':{'hex':'1101', 'name':'PDC_MessageClass', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 75 '1102':{'hex':'1102', 'name':'PDC_PresentationOption', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 76 '1103':{'hex':'1103', 'name':'PDC_AlertMechanism', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 76 '1104':{'hex':'1104', 'name':'PDC_Teleservice', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 77 '1105':{'hex':'1105', 'name':'PDC_MultiPartMessage', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 77 '1106':{'hex':'1106', 'name':'PDC_PredefinedMsg', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 78 '1201':{'hex':'1201', 'name':'display_time', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.26, page 148 '1203':{'hex':'1203', 'name':'sms_signal', 'type':'integer', 'tech':'TDMA'}, # SMPP v3.4, section 5.3.2.40, page 158 '1204':{'hex':'1204', 'name':'ms_validity', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.27, page 149 '1304':{'hex':'1304', 'name':'IS95A_AlertOnDelivery', 'type':None, 'tech':'CDMA'}, # v4 page 85 '1306':{'hex':'1306', 'name':'IS95A_LanguageIndicator', 'type':None, 'tech':'CDMA'}, # v4 page 86 '130c':{'hex':'130c', 'name':'alert_on_message_delivery', 'type':None, 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.41, page 159 '1380':{'hex':'1380', 'name':'its_reply_type', 'type':'integer', 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.42, page 159 '1383':{'hex':'1383', 'name':'its_session_info', 'type':'hex', 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.43, page 160 '1402':{'hex':'1402', 'name':'operator_id', 'type':None, 'tech':'vendor extension'}, '1403':{'hex':'1403', 'name':'tariff', 'type':None, 'tech':'Mobile Network Code vendor extension'}, '1450':{'hex':'1450', 'name':'mcc', 'type':None, 'tech':'Mobile Country Code vendor extension'}, '1451':{'hex':'1451', 'name':'mnc', 'type':None, 'tech':'Mobile Network Code vendor extension'} } def optional_parameter_tag_name_by_hex(x): return optional_parameter_tag_by_hex.get(x,{}).get('name') def optional_parameter_tag_type_by_hex(x): return optional_parameter_tag_by_hex.get(x,{}).get('type') optional_parameter_tag_by_name = { 'dest_addr_subunit' :{'hex':'0005', 'name':'dest_addr_subunit', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.1, page 134 'dest_network_type' :{'hex':'0006', 'name':'dest_network_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.3, page 135 'dest_bearer_type' :{'hex':'0007', 'name':'dest_bearer_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.5, page 136 'dest_telematics_id' :{'hex':'0008', 'name':'dest_telematics_id', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.7, page 137 'source_addr_subunit' :{'hex':'000d', 'name':'source_addr_subunit', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.2, page 134 'source_network_type' :{'hex':'000e', 'name':'source_network_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.4, page 135 'source_bearer_type' :{'hex':'000f', 'name':'source_bearer_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.6, page 136 'source_telematics_id' :{'hex':'0010', 'name':'source_telematics_id', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.8, page 137 'qos_time_to_live' :{'hex':'0017', 'name':'qos_time_to_live', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.9, page 138 'payload_type' :{'hex':'0019', 'name':'payload_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.10, page 138 'additional_status_info_text' :{'hex':'001d', 'name':'additional_status_info_text', 'type':'string', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.11, page 139 'receipted_message_id' :{'hex':'001e', 'name':'receipted_message_id', 'type':'string', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.12, page 139 'ms_msg_wait_facilities' :{'hex':'0030', 'name':'ms_msg_wait_facilities', 'type':'bitmask', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.13, page 140 'PVCY_AuthenticationStr' :{'hex':'0101', 'name':'PVCY_AuthenticationStr', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 58-62 'privacy_indicator' :{'hex':'0201', 'name':'privacy_indicator', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.14, page 141 'source_subaddress' :{'hex':'0202', 'name':'source_subaddress', 'type':'hex', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.15, page 142 'dest_subaddress' :{'hex':'0203', 'name':'dest_subaddress', 'type':'hex', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.16, page 143 'user_message_reference' :{'hex':'0204', 'name':'user_message_reference', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.17, page 143 'user_response_code' :{'hex':'0205', 'name':'user_response_code', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.18, page 144 'source_port' :{'hex':'020a', 'name':'source_port', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.20, page 145 'destination_port' :{'hex':'020b', 'name':'destination_port', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.21, page 145 'sar_msg_ref_num' :{'hex':'020c', 'name':'sar_msg_ref_num', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.22, page 146 'language_indicator' :{'hex':'020d', 'name':'language_indicator', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.19, page 144 'sar_total_segments' :{'hex':'020e', 'name':'sar_total_segments', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.23, page 147 'sar_segment_seqnum' :{'hex':'020f', 'name':'sar_segment_seqnum', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.24, page 147 'sc_interface_version' :{'hex':'0210', 'name':'sc_interface_version', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.25, page 148 'CC_CBN' :{'hex':'0301', 'name':'CC_CBN', 'type':None, 'tech':'V4'}, # v4 page 70 'callback_num_pres_ind' :{'hex':'0302', 'name':'callback_num_pres_ind', 'type':'bitmask', 'tech':'TDMA'}, # SMPP v3.4, section 5.3.2.37, page 156 'callback_num_atag' :{'hex':'0303', 'name':'callback_num_atag', 'type':'hex', 'tech':'TDMA'}, # SMPP v3.4, section 5.3.2.38, page 157 'number_of_messages' :{'hex':'0304', 'name':'number_of_messages', 'type':'integer', 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.39, page 158 'callback_num' :{'hex':'0381', 'name':'callback_num', 'type':'hex', 'tech':'CDMA, TDMA, GSM, iDEN'}, # SMPP v3.4, section 5.3.2.36, page 155 'dpf_result' :{'hex':'0420', 'name':'dpf_result', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.28, page 149 'set_dpf' :{'hex':'0421', 'name':'set_dpf', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.29, page 150 'ms_availability_status' :{'hex':'0422', 'name':'ms_availability_status', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.30, page 151 'network_error_code' :{'hex':'0423', 'name':'network_error_code', 'type':'hex', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.31, page 152 'message_payload' :{'hex':'0424', 'name':'message_payload', 'type':'hex', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.32, page 153 'delivery_failure_reason' :{'hex':'0425', 'name':'delivery_failure_reason', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.33, page 153 'more_messages_to_send' :{'hex':'0426', 'name':'more_messages_to_send', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.34, page 154 'message_state' :{'hex':'0427', 'name':'message_state', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.35, page 154 'congestion_state' :{'hex':'0428', 'name':'congestion_state', 'type':None, 'tech':'Generic'}, 'ussd_service_op' :{'hex':'0501', 'name':'ussd_service_op', 'type':'hex', 'tech':'GSM (USSD)'}, # SMPP v3.4, section 5.3.2.44, page 161 'broadcast_channel_indicator' :{'hex':'0600', 'name':'broadcast_channel_indicator', 'type':None, 'tech':'GSM'}, 'broadcast_content_type' :{'hex':'0601', 'name':'broadcast_content_type', 'type':None, 'tech':'CDMA, TDMA, GSM'}, 'broadcast_content_type_info' :{'hex':'0602', 'name':'broadcast_content_type_info', 'type':None, 'tech':'CDMA, TDMA'}, 'broadcast_message_class' :{'hex':'0603', 'name':'broadcast_message_class', 'type':None, 'tech':'GSM'}, 'broadcast_rep_num' :{'hex':'0604', 'name':'broadcast_rep_num', 'type':None, 'tech':'GSM'}, 'broadcast_frequency_interval':{'hex':'0605', 'name':'broadcast_frequency_interval', 'type':None, 'tech':'CDMA, TDMA, GSM'}, 'broadcast_area_identifier' :{'hex':'0606', 'name':'broadcast_area_identifier', 'type':None, 'tech':'CDMA, TDMA, GSM'}, 'broadcast_error_status' :{'hex':'0607', 'name':'broadcast_error_status', 'type':None, 'tech':'CDMA, TDMA, GSM'}, 'broadcast_area_success' :{'hex':'0608', 'name':'broadcast_area_success', 'type':None, 'tech':'GSM'}, 'broadcast_end_time' :{'hex':'0609', 'name':'broadcast_end_time', 'type':None, 'tech':'CDMA, TDMA, GSM'}, 'broadcast_service_group' :{'hex':'060a', 'name':'broadcast_service_group', 'type':None, 'tech':'CDMA, TDMA'}, 'billing_identification' :{'hex':'060b', 'name':'billing_identification', 'type':None, 'tech':'Generic'}, 'source_network_id' :{'hex':'060d', 'name':'source_network_id', 'type':None, 'tech':'Generic'}, 'dest_network_id' :{'hex':'060e', 'name':'dest_network_id', 'type':None, 'tech':'Generic'}, 'source_node_id' :{'hex':'060f', 'name':'source_node_id', 'type':None, 'tech':'Generic'}, 'dest_node_id' :{'hex':'0610', 'name':'dest_node_id', 'type':None, 'tech':'Generic'}, 'dest_addr_np_resolution' :{'hex':'0611', 'name':'dest_addr_np_resolution', 'type':None, 'tech':'CDMA, TDMA (US Only)'}, 'dest_addr_np_information' :{'hex':'0612', 'name':'dest_addr_np_information', 'type':None, 'tech':'CDMA, TDMA (US Only)'}, 'dest_addr_np_country' :{'hex':'0613', 'name':'dest_addr_np_country', 'type':None, 'tech':'CDMA, TDMA (US Only)'}, 'PDC_MessageClass' :{'hex':'1101', 'name':'PDC_MessageClass', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 75 'PDC_PresentationOption' :{'hex':'1102', 'name':'PDC_PresentationOption', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 76 'PDC_AlertMechanism' :{'hex':'1103', 'name':'PDC_AlertMechanism', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 76 'PDC_Teleservice' :{'hex':'1104', 'name':'PDC_Teleservice', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 77 'PDC_MultiPartMessage' :{'hex':'1105', 'name':'PDC_MultiPartMessage', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 77 'PDC_PredefinedMsg' :{'hex':'1106', 'name':'PDC_PredefinedMsg', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 78 'display_time' :{'hex':'1201', 'name':'display_time', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.26, page 148 'sms_signal' :{'hex':'1203', 'name':'sms_signal', 'type':'integer', 'tech':'TDMA'}, # SMPP v3.4, section 5.3.2.40, page 158 'ms_validity' :{'hex':'1204', 'name':'ms_validity', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.27, page 149 'IS95A_AlertOnDelivery' :{'hex':'1304', 'name':'IS95A_AlertOnDelivery', 'type':None, 'tech':'CDMA'}, # v4 page 85 'IS95A_LanguageIndicator' :{'hex':'1306', 'name':'IS95A_LanguageIndicator', 'type':None, 'tech':'CDMA'}, # v4 page 86 'alert_on_message_delivery' :{'hex':'130c', 'name':'alert_on_message_delivery', 'type':None, 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.41, page 159 'its_reply_type' :{'hex':'1380', 'name':'its_reply_type', 'type':'integer', 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.42, page 159 'its_session_info' :{'hex':'1383', 'name':'its_session_info', 'type':'hex', 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.43, page 160 'operator_id' :{'hex':'1402', 'name':'operator_id', 'type':None, 'tech':'vendor extension'}, 'tariff' :{'hex':'1403', 'name':'tariff', 'type':None, 'tech':'Mobile Network Code vendor extension'}, 'mcc' :{'hex':'1450', 'name':'mcc', 'type':None, 'tech':'Mobile Country Code vendor extension'}, 'mnc' :{'hex':'1451', 'name':'mnc', 'type':None, 'tech':'Mobile Network Code vendor extension'} } def optional_parameter_tag_hex_by_name(n): return optional_parameter_tag_by_name.get(n,{}).get('hex') #### Decoding functions ####################################################### def unpack_pdu(pdu_bin): return decode_pdu(binascii.b2a_hex(pdu_bin)) def decode_pdu(pdu_hex): hex_ref = [pdu_hex] pdu = {} pdu['header'] = decode_header(hex_ref) command = pdu['header'].get('command_id', None) if command != None: body = decode_body(command, hex_ref) if len(body) > 0: pdu['body'] = body return pdu def decode_header(hex_ref): pdu_hex = hex_ref[0] header = {} (command_length, command_id, command_status, sequence_number, hex_ref[0]) = \ (pdu_hex[0:8], pdu_hex[8:16], pdu_hex[16:24], pdu_hex[24:32], pdu_hex[32: ]) length = int(command_length, 16) command = command_id_name_by_hex(command_id) status = command_status_name_by_hex(command_status) sequence = int(sequence_number, 16) header = {} header['command_length'] = length header['command_id'] = command header['command_status'] = status header['sequence_number'] = sequence return header def decode_body(command, hex_ref): body = {} if command != None: fields = mandatory_parameter_list_by_command_name(command) mandatory = decode_mandatory_parameters(fields, hex_ref) if len(mandatory) > 0: body['mandatory_parameters'] = mandatory optional = decode_optional_parameters(hex_ref) if len(optional) > 0: body['optional_parameters'] = optional return body def decode_mandatory_parameters(fields, hex_ref): mandatory_parameters = {} if len(hex_ref[0]) > 1: for field in fields: #old = len(hex_ref[0]) data = '' octet = '' count = 0 if field['var'] == True or field['var'] == False: while (len(hex_ref[0]) > 1 and (count < field['min'] or (field['var'] == True and count < field['max']+1 and octet != '00'))): octet = octpop(hex_ref) data += octet count += 1 elif field['type'] in ['string', 'xstring']: count = mandatory_parameters[field['var']] if count == 0: data = None else: for i in range(count): if len(hex_ref[0]) > 1: data += octpop(hex_ref) else: count = mandatory_parameters[field['var']] if field['map'] != None: mandatory_parameters[field['name']] = maps[field['map']+'_by_hex'].get(data, None) if field['map'] == None or mandatory_parameters[field['name']] == None: mandatory_parameters[field['name']] = decode_hex_type(data, field['type'], count, hex_ref) #print field['type'], (old - len(hex_ref[0]))/2, repr(data), field['name'], mandatory_parameters[field['name']] return mandatory_parameters def decode_optional_parameters(hex_ref): optional_parameters = [] hex = hex_ref[0] while len(hex) > 0: (tag_hex, length_hex, rest) = (hex[0:4], hex[4:8], hex[8: ]) tag = optional_parameter_tag_name_by_hex(tag_hex) if tag == None: tag = tag_hex length = int(length_hex, 16) (value_hex, tail) = (rest[0:length*2], rest[length*2: ]) if len(value_hex) == 0: value = None else: value = decode_hex_type(value_hex, optional_parameter_tag_type_by_hex(tag_hex)) hex = tail optional_parameters.append({'tag':tag, 'length':length, 'value':value}) return optional_parameters def decode_hex_type(hex, type, count=0, hex_ref=['']): if hex == None: return hex elif type == 'integer': return int(hex, 16) elif type == 'string': return re.sub('00','',hex).decode('hex') elif type == 'xstring': return hex.decode('hex') elif (type == 'dest_address' or type == 'unsuccess_sme'): list = [] fields = mandatory_parameter_list_by_command_name(type) for i in range(count): item = decode_mandatory_parameters(fields, hex_ref) if item.get('dest_flag', None) == 1: # 'dest_address' only subfields = mandatory_parameter_list_by_command_name('sme_dest_address') rest = decode_mandatory_parameters(subfields, hex_ref) item.update(rest) elif item.get('dest_flag', None) == 2: # 'dest_address' only subfields = mandatory_parameter_list_by_command_name('distribution_list') rest = decode_mandatory_parameters(subfields, hex_ref) item.update(rest) list.append(item) return list else: return hex def octpop(hex_ref): octet = None if len(hex_ref[0]) > 1: (octet, hex_ref[0]) = (hex_ref[0][0:2], hex_ref[0][2: ]) return octet #### Encoding functions ####################################################### def pack_pdu(pdu_obj): return binascii.a2b_hex(encode_pdu(pdu_obj)) def encode_pdu(pdu_obj): header = pdu_obj.get('header', {}) body = pdu_obj.get('body', {}) mandatory = body.get('mandatory_parameters', {}) optional = body.get('optional_parameters', []) body_hex = '' fields = mandatory_parameter_list_by_command_name(header['command_id']) body_hex += encode_mandatory_parameters(mandatory, fields) for opt in optional: body_hex += encode_optional_parameter(opt['tag'], opt['value']) actual_length = 16 + len(body_hex)/2 command_length = '%08x' % actual_length command_id = command_id_hex_by_name(header['command_id']) command_status = command_status_hex_by_name(header['command_status']) sequence_number = '%08x' % header['sequence_number'] pdu_hex = command_length + command_id + command_status + sequence_number + body_hex return pdu_hex def encode_mandatory_parameters(mandatory_obj, fields): mandatory_hex_array = [] index_names = {} index = 0 for field in fields: param = mandatory_obj.get(field['name'], None) param_length = None if param != None or field['min'] > 0: map = None if field['map'] != None: map = maps.get(field['map']+'_by_name', None) if isinstance(param, list): hex_list = [] for item in param: flagfields = mandatory_parameter_list_by_command_name(field['type']) plusfields = [] if item.get('dest_flag', None) == 1: plusfields = mandatory_parameter_list_by_command_name('sme_dest_address') elif item.get('dest_flag', None) == 2: plusfields = mandatory_parameter_list_by_command_name('distribution_list') hex_item = encode_mandatory_parameters(item, flagfields + plusfields) if isinstance(hex_item, str) and len(hex_item) > 0: hex_list.append(hex_item) param_length = len(hex_list) mandatory_hex_array.append(''.join(hex_list)) else: hex_param = encode_param_type( param, field['type'], field['min'], field['max'], map) param_length = len(hex_param)/2 mandatory_hex_array.append(hex_param) index_names[field['name']] = index length_index = index_names.get(field['var'], None) if length_index != None and param_length != None: mandatory_hex_array[length_index] = encode_param_type( param_length, 'integer', len(mandatory_hex_array[length_index])/2) index += 1 return ''.join(mandatory_hex_array) def encode_optional_parameter(tag, value): optional_hex_array = [] tag_hex = optional_parameter_tag_hex_by_name(tag) if tag_hex != None: value_hex = encode_param_type( value, optional_parameter_tag_type_by_hex(tag_hex)) length_hex = '%04x' % (len(value_hex)/2) optional_hex_array.append(tag_hex + length_hex + value_hex) return ''.join(optional_hex_array) -def encode_param_type(param, type, min=0, max=None, map=None): +def encode_param_type(param, type, min=1, max=None, map=None): if param == None: hex = None elif map != None: if type == 'integer' and isinstance(param, int): hex = ('%0'+str(min*2)+'x') % param else: hex = map.get(param, ('%0'+str(min*2)+'x') % 0) elif type == 'integer': - hex = ('%0'+str((min or 0)*2)+'x') % int(param) - print "min:", min, "HEX:",hex + hex = ('%0'+str(min*2)+'x') % int(param) + print "HEX: ",hex elif type == 'string': hex = param.encode('hex') + '00' elif type == 'xstring': hex = param.encode('hex') elif type == 'bitmask': hex = param elif type == 'hex': hex = param else: hex = None #if hex == None: #hex = '' #if min > 0: #hex = ('%0'+str(min*2)+'x') % 0 #print type, min, max, repr(param), hex, map return hex
dmaclay/python-smpp
84a1ec7c1b6c1c6ee7cc531d331b76591ae68f03
less disruptive
diff --git a/smpp/pdu.py b/smpp/pdu.py index e6a2e25..d4fdc42 100644 --- a/smpp/pdu.py +++ b/smpp/pdu.py @@ -507,541 +507,541 @@ maps['esm_class_bits'] = { 'feature_mask' :'c0', 'mode_default' :'00', 'mode_datagram' :'01', 'mode_forward' :'02', 'mode_store_and_forward' :'03', 'type_default' :'00', 'type_delivery_receipt' :'04', 'type_delivery_ack' :'08', 'type_0011' :'0a', 'type_user_ack' :'10', 'type_0101' :'14', 'type_conversation_abort' :'18', 'type_0111' :'1a', 'type_intermed_deliv_notif' :'20', 'type_1001' :'24', 'type_1010' :'28', 'type_1011' :'2a', 'type_1100' :'30', 'type_1101' :'34', 'type_1110' :'38', 'type_1111' :'3a', 'feature_none' :'00', 'feature_UDHI' :'40', 'feature_reply_path' :'80', 'feature_UDHI_and_reply_path':'c0' } # Registered Delivery bits - SMPP v3.4, section 5.2.17, page 124 maps['registered_delivery_bits'] = { 'receipt_mask' :'03', 'ack_mask' :'0c', 'intermed_notif_mask' :'80', 'receipt_none' :'00', 'receipt_always' :'01', 'receipt_on_fail' :'02', 'receipt_res' :'03', 'ack_none' :'00', 'ack_delivery' :'04', 'ack_user' :'08', 'ack_delivery_and_user':'0c', 'intermed_notif_none' :'00', 'intermed_notif' :'10' } # submit_multi dest_flag constants - SMPP v3.4, section 5.2.25, page 129 #maps['dest_flag_by_name'] = { #'SME Address' :1, #'Distribution List Name':2 #} # Message State codes returned in query_sm_resp PDUs - SMPP v3.4, section 5.2.28, table 5-6, page 130 maps['message_state_by_name'] = { 'ENROUTE' :1, 'DELIVERED' :2, 'EXPIRED' :3, 'DELETED' :4, 'UNDELIVERABLE':5, 'ACCEPTED' :6, 'UNKNOWN' :7, 'REJECTED' :8 } # Facility Code bits for SMPP v4 maps['facility_code_bits'] = { 'GF_PVCY' :'00000001', 'GF_SUBADDR':'00000002', 'NF_CC' :'00080000', 'NF_PDC' :'00010000', 'NF_IS136' :'00020000', 'NF_IS95A' :'00040000' } # Optional Parameter Tags - SMPP v3.4, section 5.3.2, Table 5-7, page 132-133 optional_parameter_tag_by_hex = { '0005':{'hex':'0005', 'name':'dest_addr_subunit', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.1, page 134 '0006':{'hex':'0006', 'name':'dest_network_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.3, page 135 '0007':{'hex':'0007', 'name':'dest_bearer_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.5, page 136 '0008':{'hex':'0008', 'name':'dest_telematics_id', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.7, page 137 '000d':{'hex':'000d', 'name':'source_addr_subunit', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.2, page 134 '000e':{'hex':'000e', 'name':'source_network_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.4, page 135 '000f':{'hex':'000f', 'name':'source_bearer_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.6, page 136 '0010':{'hex':'0010', 'name':'source_telematics_id', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.8, page 137 '0017':{'hex':'0017', 'name':'qos_time_to_live', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.9, page 138 '0019':{'hex':'0019', 'name':'payload_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.10, page 138 '001d':{'hex':'001d', 'name':'additional_status_info_text', 'type':'string', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.11, page 139 '001e':{'hex':'001e', 'name':'receipted_message_id', 'type':'string', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.12, page 139 '0030':{'hex':'0030', 'name':'ms_msg_wait_facilities', 'type':'bitmask', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.13, page 140 '0101':{'hex':'0101', 'name':'PVCY_AuthenticationStr', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 58-62 '0201':{'hex':'0201', 'name':'privacy_indicator', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.14, page 141 '0202':{'hex':'0202', 'name':'source_subaddress', 'type':'hex', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.15, page 142 '0203':{'hex':'0203', 'name':'dest_subaddress', 'type':'hex', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.16, page 143 '0204':{'hex':'0204', 'name':'user_message_reference', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.17, page 143 '0205':{'hex':'0205', 'name':'user_response_code', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.18, page 144 '020a':{'hex':'020a', 'name':'source_port', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.20, page 145 '020b':{'hex':'020b', 'name':'destination_port', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.21, page 145 '020c':{'hex':'020c', 'name':'sar_msg_ref_num', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.22, page 146 '020d':{'hex':'020d', 'name':'language_indicator', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.19, page 144 '020e':{'hex':'020e', 'name':'sar_total_segments', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.23, page 147 '020f':{'hex':'020f', 'name':'sar_segment_seqnum', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.24, page 147 '0210':{'hex':'0210', 'name':'sc_interface_version', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.25, page 148 '0301':{'hex':'0301', 'name':'CC_CBN', 'type':None, 'tech':'V4'}, # v4 page 70 '0302':{'hex':'0302', 'name':'callback_num_pres_ind', 'type':'bitmask', 'tech':'TDMA'}, # SMPP v3.4, section 5.3.2.37, page 156 '0303':{'hex':'0303', 'name':'callback_num_atag', 'type':'hex', 'tech':'TDMA'}, # SMPP v3.4, section 5.3.2.38, page 157 '0304':{'hex':'0304', 'name':'number_of_messages', 'type':'integer', 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.39, page 158 '0381':{'hex':'0381', 'name':'callback_num', 'type':'hex', 'tech':'CDMA, TDMA, GSM, iDEN'}, # SMPP v3.4, section 5.3.2.36, page 155 '0420':{'hex':'0420', 'name':'dpf_result', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.28, page 149 '0421':{'hex':'0421', 'name':'set_dpf', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.29, page 150 '0422':{'hex':'0422', 'name':'ms_availability_status', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.30, page 151 '0423':{'hex':'0423', 'name':'network_error_code', 'type':'hex', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.31, page 152 '0424':{'hex':'0424', 'name':'message_payload', 'type':'hex', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.32, page 153 '0425':{'hex':'0425', 'name':'delivery_failure_reason', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.33, page 153 '0426':{'hex':'0426', 'name':'more_messages_to_send', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.34, page 154 '0427':{'hex':'0427', 'name':'message_state', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.35, page 154 '0428':{'hex':'0428', 'name':'congestion_state', 'type':None, 'tech':'Generic'}, '0501':{'hex':'0501', 'name':'ussd_service_op', 'type':'hex', 'tech':'GSM (USSD)'}, # SMPP v3.4, section 5.3.2.44, page 161 '0600':{'hex':'0600', 'name':'broadcast_channel_indicator', 'type':None, 'tech':'GSM'}, '0601':{'hex':'0601', 'name':'broadcast_content_type', 'type':None, 'tech':'CDMA, TDMA, GSM'}, '0602':{'hex':'0602', 'name':'broadcast_content_type_info', 'type':None, 'tech':'CDMA, TDMA'}, '0603':{'hex':'0603', 'name':'broadcast_message_class', 'type':None, 'tech':'GSM'}, '0604':{'hex':'0604', 'name':'broadcast_rep_num', 'type':None, 'tech':'GSM'}, '0605':{'hex':'0605', 'name':'broadcast_frequency_interval', 'type':None, 'tech':'CDMA, TDMA, GSM'}, '0606':{'hex':'0606', 'name':'broadcast_area_identifier', 'type':None, 'tech':'CDMA, TDMA, GSM'}, '0607':{'hex':'0607', 'name':'broadcast_error_status', 'type':None, 'tech':'CDMA, TDMA, GSM'}, '0608':{'hex':'0608', 'name':'broadcast_area_success', 'type':None, 'tech':'GSM'}, '0609':{'hex':'0609', 'name':'broadcast_end_time', 'type':None, 'tech':'CDMA, TDMA, GSM'}, '060a':{'hex':'060a', 'name':'broadcast_service_group', 'type':None, 'tech':'CDMA, TDMA'}, '060b':{'hex':'060b', 'name':'billing_identification', 'type':None, 'tech':'Generic'}, '060d':{'hex':'060d', 'name':'source_network_id', 'type':None, 'tech':'Generic'}, '060e':{'hex':'060e', 'name':'dest_network_id', 'type':None, 'tech':'Generic'}, '060f':{'hex':'060f', 'name':'source_node_id', 'type':None, 'tech':'Generic'}, '0610':{'hex':'0610', 'name':'dest_node_id', 'type':None, 'tech':'Generic'}, '0611':{'hex':'0611', 'name':'dest_addr_np_resolution', 'type':None, 'tech':'CDMA, TDMA (US Only)'}, '0612':{'hex':'0612', 'name':'dest_addr_np_information', 'type':None, 'tech':'CDMA, TDMA (US Only)'}, '0613':{'hex':'0613', 'name':'dest_addr_np_country', 'type':None, 'tech':'CDMA, TDMA (US Only)'}, '1101':{'hex':'1101', 'name':'PDC_MessageClass', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 75 '1102':{'hex':'1102', 'name':'PDC_PresentationOption', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 76 '1103':{'hex':'1103', 'name':'PDC_AlertMechanism', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 76 '1104':{'hex':'1104', 'name':'PDC_Teleservice', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 77 '1105':{'hex':'1105', 'name':'PDC_MultiPartMessage', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 77 '1106':{'hex':'1106', 'name':'PDC_PredefinedMsg', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 78 '1201':{'hex':'1201', 'name':'display_time', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.26, page 148 '1203':{'hex':'1203', 'name':'sms_signal', 'type':'integer', 'tech':'TDMA'}, # SMPP v3.4, section 5.3.2.40, page 158 '1204':{'hex':'1204', 'name':'ms_validity', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.27, page 149 '1304':{'hex':'1304', 'name':'IS95A_AlertOnDelivery', 'type':None, 'tech':'CDMA'}, # v4 page 85 '1306':{'hex':'1306', 'name':'IS95A_LanguageIndicator', 'type':None, 'tech':'CDMA'}, # v4 page 86 '130c':{'hex':'130c', 'name':'alert_on_message_delivery', 'type':None, 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.41, page 159 '1380':{'hex':'1380', 'name':'its_reply_type', 'type':'integer', 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.42, page 159 '1383':{'hex':'1383', 'name':'its_session_info', 'type':'hex', 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.43, page 160 '1402':{'hex':'1402', 'name':'operator_id', 'type':None, 'tech':'vendor extension'}, '1403':{'hex':'1403', 'name':'tariff', 'type':None, 'tech':'Mobile Network Code vendor extension'}, '1450':{'hex':'1450', 'name':'mcc', 'type':None, 'tech':'Mobile Country Code vendor extension'}, '1451':{'hex':'1451', 'name':'mnc', 'type':None, 'tech':'Mobile Network Code vendor extension'} } def optional_parameter_tag_name_by_hex(x): return optional_parameter_tag_by_hex.get(x,{}).get('name') def optional_parameter_tag_type_by_hex(x): return optional_parameter_tag_by_hex.get(x,{}).get('type') optional_parameter_tag_by_name = { 'dest_addr_subunit' :{'hex':'0005', 'name':'dest_addr_subunit', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.1, page 134 'dest_network_type' :{'hex':'0006', 'name':'dest_network_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.3, page 135 'dest_bearer_type' :{'hex':'0007', 'name':'dest_bearer_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.5, page 136 'dest_telematics_id' :{'hex':'0008', 'name':'dest_telematics_id', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.7, page 137 'source_addr_subunit' :{'hex':'000d', 'name':'source_addr_subunit', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.2, page 134 'source_network_type' :{'hex':'000e', 'name':'source_network_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.4, page 135 'source_bearer_type' :{'hex':'000f', 'name':'source_bearer_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.6, page 136 'source_telematics_id' :{'hex':'0010', 'name':'source_telematics_id', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.8, page 137 'qos_time_to_live' :{'hex':'0017', 'name':'qos_time_to_live', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.9, page 138 'payload_type' :{'hex':'0019', 'name':'payload_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.10, page 138 'additional_status_info_text' :{'hex':'001d', 'name':'additional_status_info_text', 'type':'string', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.11, page 139 'receipted_message_id' :{'hex':'001e', 'name':'receipted_message_id', 'type':'string', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.12, page 139 'ms_msg_wait_facilities' :{'hex':'0030', 'name':'ms_msg_wait_facilities', 'type':'bitmask', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.13, page 140 'PVCY_AuthenticationStr' :{'hex':'0101', 'name':'PVCY_AuthenticationStr', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 58-62 'privacy_indicator' :{'hex':'0201', 'name':'privacy_indicator', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.14, page 141 'source_subaddress' :{'hex':'0202', 'name':'source_subaddress', 'type':'hex', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.15, page 142 'dest_subaddress' :{'hex':'0203', 'name':'dest_subaddress', 'type':'hex', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.16, page 143 'user_message_reference' :{'hex':'0204', 'name':'user_message_reference', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.17, page 143 'user_response_code' :{'hex':'0205', 'name':'user_response_code', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.18, page 144 'source_port' :{'hex':'020a', 'name':'source_port', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.20, page 145 'destination_port' :{'hex':'020b', 'name':'destination_port', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.21, page 145 'sar_msg_ref_num' :{'hex':'020c', 'name':'sar_msg_ref_num', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.22, page 146 'language_indicator' :{'hex':'020d', 'name':'language_indicator', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.19, page 144 'sar_total_segments' :{'hex':'020e', 'name':'sar_total_segments', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.23, page 147 'sar_segment_seqnum' :{'hex':'020f', 'name':'sar_segment_seqnum', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.24, page 147 'sc_interface_version' :{'hex':'0210', 'name':'sc_interface_version', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.25, page 148 'CC_CBN' :{'hex':'0301', 'name':'CC_CBN', 'type':None, 'tech':'V4'}, # v4 page 70 'callback_num_pres_ind' :{'hex':'0302', 'name':'callback_num_pres_ind', 'type':'bitmask', 'tech':'TDMA'}, # SMPP v3.4, section 5.3.2.37, page 156 'callback_num_atag' :{'hex':'0303', 'name':'callback_num_atag', 'type':'hex', 'tech':'TDMA'}, # SMPP v3.4, section 5.3.2.38, page 157 'number_of_messages' :{'hex':'0304', 'name':'number_of_messages', 'type':'integer', 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.39, page 158 'callback_num' :{'hex':'0381', 'name':'callback_num', 'type':'hex', 'tech':'CDMA, TDMA, GSM, iDEN'}, # SMPP v3.4, section 5.3.2.36, page 155 'dpf_result' :{'hex':'0420', 'name':'dpf_result', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.28, page 149 'set_dpf' :{'hex':'0421', 'name':'set_dpf', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.29, page 150 'ms_availability_status' :{'hex':'0422', 'name':'ms_availability_status', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.30, page 151 'network_error_code' :{'hex':'0423', 'name':'network_error_code', 'type':'hex', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.31, page 152 'message_payload' :{'hex':'0424', 'name':'message_payload', 'type':'hex', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.32, page 153 'delivery_failure_reason' :{'hex':'0425', 'name':'delivery_failure_reason', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.33, page 153 'more_messages_to_send' :{'hex':'0426', 'name':'more_messages_to_send', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.34, page 154 'message_state' :{'hex':'0427', 'name':'message_state', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.35, page 154 'congestion_state' :{'hex':'0428', 'name':'congestion_state', 'type':None, 'tech':'Generic'}, 'ussd_service_op' :{'hex':'0501', 'name':'ussd_service_op', 'type':'hex', 'tech':'GSM (USSD)'}, # SMPP v3.4, section 5.3.2.44, page 161 'broadcast_channel_indicator' :{'hex':'0600', 'name':'broadcast_channel_indicator', 'type':None, 'tech':'GSM'}, 'broadcast_content_type' :{'hex':'0601', 'name':'broadcast_content_type', 'type':None, 'tech':'CDMA, TDMA, GSM'}, 'broadcast_content_type_info' :{'hex':'0602', 'name':'broadcast_content_type_info', 'type':None, 'tech':'CDMA, TDMA'}, 'broadcast_message_class' :{'hex':'0603', 'name':'broadcast_message_class', 'type':None, 'tech':'GSM'}, 'broadcast_rep_num' :{'hex':'0604', 'name':'broadcast_rep_num', 'type':None, 'tech':'GSM'}, 'broadcast_frequency_interval':{'hex':'0605', 'name':'broadcast_frequency_interval', 'type':None, 'tech':'CDMA, TDMA, GSM'}, 'broadcast_area_identifier' :{'hex':'0606', 'name':'broadcast_area_identifier', 'type':None, 'tech':'CDMA, TDMA, GSM'}, 'broadcast_error_status' :{'hex':'0607', 'name':'broadcast_error_status', 'type':None, 'tech':'CDMA, TDMA, GSM'}, 'broadcast_area_success' :{'hex':'0608', 'name':'broadcast_area_success', 'type':None, 'tech':'GSM'}, 'broadcast_end_time' :{'hex':'0609', 'name':'broadcast_end_time', 'type':None, 'tech':'CDMA, TDMA, GSM'}, 'broadcast_service_group' :{'hex':'060a', 'name':'broadcast_service_group', 'type':None, 'tech':'CDMA, TDMA'}, 'billing_identification' :{'hex':'060b', 'name':'billing_identification', 'type':None, 'tech':'Generic'}, 'source_network_id' :{'hex':'060d', 'name':'source_network_id', 'type':None, 'tech':'Generic'}, 'dest_network_id' :{'hex':'060e', 'name':'dest_network_id', 'type':None, 'tech':'Generic'}, 'source_node_id' :{'hex':'060f', 'name':'source_node_id', 'type':None, 'tech':'Generic'}, 'dest_node_id' :{'hex':'0610', 'name':'dest_node_id', 'type':None, 'tech':'Generic'}, 'dest_addr_np_resolution' :{'hex':'0611', 'name':'dest_addr_np_resolution', 'type':None, 'tech':'CDMA, TDMA (US Only)'}, 'dest_addr_np_information' :{'hex':'0612', 'name':'dest_addr_np_information', 'type':None, 'tech':'CDMA, TDMA (US Only)'}, 'dest_addr_np_country' :{'hex':'0613', 'name':'dest_addr_np_country', 'type':None, 'tech':'CDMA, TDMA (US Only)'}, 'PDC_MessageClass' :{'hex':'1101', 'name':'PDC_MessageClass', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 75 'PDC_PresentationOption' :{'hex':'1102', 'name':'PDC_PresentationOption', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 76 'PDC_AlertMechanism' :{'hex':'1103', 'name':'PDC_AlertMechanism', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 76 'PDC_Teleservice' :{'hex':'1104', 'name':'PDC_Teleservice', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 77 'PDC_MultiPartMessage' :{'hex':'1105', 'name':'PDC_MultiPartMessage', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 77 'PDC_PredefinedMsg' :{'hex':'1106', 'name':'PDC_PredefinedMsg', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 78 'display_time' :{'hex':'1201', 'name':'display_time', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.26, page 148 'sms_signal' :{'hex':'1203', 'name':'sms_signal', 'type':'integer', 'tech':'TDMA'}, # SMPP v3.4, section 5.3.2.40, page 158 'ms_validity' :{'hex':'1204', 'name':'ms_validity', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.27, page 149 'IS95A_AlertOnDelivery' :{'hex':'1304', 'name':'IS95A_AlertOnDelivery', 'type':None, 'tech':'CDMA'}, # v4 page 85 'IS95A_LanguageIndicator' :{'hex':'1306', 'name':'IS95A_LanguageIndicator', 'type':None, 'tech':'CDMA'}, # v4 page 86 'alert_on_message_delivery' :{'hex':'130c', 'name':'alert_on_message_delivery', 'type':None, 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.41, page 159 'its_reply_type' :{'hex':'1380', 'name':'its_reply_type', 'type':'integer', 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.42, page 159 'its_session_info' :{'hex':'1383', 'name':'its_session_info', 'type':'hex', 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.43, page 160 'operator_id' :{'hex':'1402', 'name':'operator_id', 'type':None, 'tech':'vendor extension'}, 'tariff' :{'hex':'1403', 'name':'tariff', 'type':None, 'tech':'Mobile Network Code vendor extension'}, 'mcc' :{'hex':'1450', 'name':'mcc', 'type':None, 'tech':'Mobile Country Code vendor extension'}, 'mnc' :{'hex':'1451', 'name':'mnc', 'type':None, 'tech':'Mobile Network Code vendor extension'} } def optional_parameter_tag_hex_by_name(n): return optional_parameter_tag_by_name.get(n,{}).get('hex') #### Decoding functions ####################################################### def unpack_pdu(pdu_bin): return decode_pdu(binascii.b2a_hex(pdu_bin)) def decode_pdu(pdu_hex): hex_ref = [pdu_hex] pdu = {} pdu['header'] = decode_header(hex_ref) command = pdu['header'].get('command_id', None) if command != None: body = decode_body(command, hex_ref) if len(body) > 0: pdu['body'] = body return pdu def decode_header(hex_ref): pdu_hex = hex_ref[0] header = {} (command_length, command_id, command_status, sequence_number, hex_ref[0]) = \ (pdu_hex[0:8], pdu_hex[8:16], pdu_hex[16:24], pdu_hex[24:32], pdu_hex[32: ]) length = int(command_length, 16) command = command_id_name_by_hex(command_id) status = command_status_name_by_hex(command_status) sequence = int(sequence_number, 16) header = {} header['command_length'] = length header['command_id'] = command header['command_status'] = status header['sequence_number'] = sequence return header def decode_body(command, hex_ref): body = {} if command != None: fields = mandatory_parameter_list_by_command_name(command) mandatory = decode_mandatory_parameters(fields, hex_ref) if len(mandatory) > 0: body['mandatory_parameters'] = mandatory optional = decode_optional_parameters(hex_ref) if len(optional) > 0: body['optional_parameters'] = optional return body def decode_mandatory_parameters(fields, hex_ref): mandatory_parameters = {} if len(hex_ref[0]) > 1: for field in fields: #old = len(hex_ref[0]) data = '' octet = '' count = 0 if field['var'] == True or field['var'] == False: while (len(hex_ref[0]) > 1 and (count < field['min'] or (field['var'] == True and count < field['max']+1 and octet != '00'))): octet = octpop(hex_ref) data += octet count += 1 elif field['type'] in ['string', 'xstring']: count = mandatory_parameters[field['var']] if count == 0: data = None else: for i in range(count): if len(hex_ref[0]) > 1: data += octpop(hex_ref) else: count = mandatory_parameters[field['var']] if field['map'] != None: mandatory_parameters[field['name']] = maps[field['map']+'_by_hex'].get(data, None) if field['map'] == None or mandatory_parameters[field['name']] == None: mandatory_parameters[field['name']] = decode_hex_type(data, field['type'], count, hex_ref) #print field['type'], (old - len(hex_ref[0]))/2, repr(data), field['name'], mandatory_parameters[field['name']] return mandatory_parameters def decode_optional_parameters(hex_ref): optional_parameters = [] hex = hex_ref[0] while len(hex) > 0: (tag_hex, length_hex, rest) = (hex[0:4], hex[4:8], hex[8: ]) tag = optional_parameter_tag_name_by_hex(tag_hex) if tag == None: tag = tag_hex length = int(length_hex, 16) (value_hex, tail) = (rest[0:length*2], rest[length*2: ]) if len(value_hex) == 0: value = None else: value = decode_hex_type(value_hex, optional_parameter_tag_type_by_hex(tag_hex)) hex = tail optional_parameters.append({'tag':tag, 'length':length, 'value':value}) return optional_parameters def decode_hex_type(hex, type, count=0, hex_ref=['']): if hex == None: return hex elif type == 'integer': return int(hex, 16) elif type == 'string': return re.sub('00','',hex).decode('hex') elif type == 'xstring': return hex.decode('hex') elif (type == 'dest_address' or type == 'unsuccess_sme'): list = [] fields = mandatory_parameter_list_by_command_name(type) for i in range(count): item = decode_mandatory_parameters(fields, hex_ref) if item.get('dest_flag', None) == 1: # 'dest_address' only subfields = mandatory_parameter_list_by_command_name('sme_dest_address') rest = decode_mandatory_parameters(subfields, hex_ref) item.update(rest) elif item.get('dest_flag', None) == 2: # 'dest_address' only subfields = mandatory_parameter_list_by_command_name('distribution_list') rest = decode_mandatory_parameters(subfields, hex_ref) item.update(rest) list.append(item) return list else: return hex def octpop(hex_ref): octet = None if len(hex_ref[0]) > 1: (octet, hex_ref[0]) = (hex_ref[0][0:2], hex_ref[0][2: ]) return octet #### Encoding functions ####################################################### def pack_pdu(pdu_obj): return binascii.a2b_hex(encode_pdu(pdu_obj)) def encode_pdu(pdu_obj): header = pdu_obj.get('header', {}) body = pdu_obj.get('body', {}) mandatory = body.get('mandatory_parameters', {}) optional = body.get('optional_parameters', []) body_hex = '' fields = mandatory_parameter_list_by_command_name(header['command_id']) body_hex += encode_mandatory_parameters(mandatory, fields) for opt in optional: body_hex += encode_optional_parameter(opt['tag'], opt['value']) actual_length = 16 + len(body_hex)/2 command_length = '%08x' % actual_length command_id = command_id_hex_by_name(header['command_id']) command_status = command_status_hex_by_name(header['command_status']) sequence_number = '%08x' % header['sequence_number'] pdu_hex = command_length + command_id + command_status + sequence_number + body_hex return pdu_hex def encode_mandatory_parameters(mandatory_obj, fields): mandatory_hex_array = [] index_names = {} index = 0 for field in fields: param = mandatory_obj.get(field['name'], None) param_length = None if param != None or field['min'] > 0: map = None if field['map'] != None: map = maps.get(field['map']+'_by_name', None) if isinstance(param, list): hex_list = [] for item in param: flagfields = mandatory_parameter_list_by_command_name(field['type']) plusfields = [] if item.get('dest_flag', None) == 1: plusfields = mandatory_parameter_list_by_command_name('sme_dest_address') elif item.get('dest_flag', None) == 2: plusfields = mandatory_parameter_list_by_command_name('distribution_list') hex_item = encode_mandatory_parameters(item, flagfields + plusfields) if isinstance(hex_item, str) and len(hex_item) > 0: hex_list.append(hex_item) param_length = len(hex_list) mandatory_hex_array.append(''.join(hex_list)) else: hex_param = encode_param_type( param, field['type'], field['min'], field['max'], map) param_length = len(hex_param)/2 mandatory_hex_array.append(hex_param) index_names[field['name']] = index length_index = index_names.get(field['var'], None) if length_index != None and param_length != None: mandatory_hex_array[length_index] = encode_param_type( param_length, 'integer', len(mandatory_hex_array[length_index])/2) index += 1 return ''.join(mandatory_hex_array) def encode_optional_parameter(tag, value): optional_hex_array = [] tag_hex = optional_parameter_tag_hex_by_name(tag) if tag_hex != None: value_hex = encode_param_type( value, optional_parameter_tag_type_by_hex(tag_hex)) length_hex = '%04x' % (len(value_hex)/2) optional_hex_array.append(tag_hex + length_hex + value_hex) return ''.join(optional_hex_array) -def encode_param_type(param, type, min=1, max=None, map=None): +def encode_param_type(param, type, min=0, max=None, map=None): if param == None: hex = None elif map != None: if type == 'integer' and isinstance(param, int): hex = ('%0'+str(min*2)+'x') % param else: hex = map.get(param, ('%0'+str(min*2)+'x') % 0) elif type == 'integer': - hex = ('%0'+str(min*2)+'x') % int(param) - print "HEX: ",hex + hex = ('%0'+str((min or 0)*2)+'x') % int(param) + print "min:", min, "HEX:",hex elif type == 'string': hex = param.encode('hex') + '00' elif type == 'xstring': hex = param.encode('hex') elif type == 'bitmask': hex = param elif type == 'hex': hex = param else: hex = None #if hex == None: #hex = '' #if min > 0: #hex = ('%0'+str(min*2)+'x') % 0 #print type, min, max, repr(param), hex, map return hex
dmaclay/python-smpp
58f454afc03f842ce3df026fb9f0edaea964137b
and that fixes it ... if it doesn't break something else
diff --git a/smpp/pdu.py b/smpp/pdu.py index b22c817..e6a2e25 100644 --- a/smpp/pdu.py +++ b/smpp/pdu.py @@ -507,541 +507,541 @@ maps['esm_class_bits'] = { 'feature_mask' :'c0', 'mode_default' :'00', 'mode_datagram' :'01', 'mode_forward' :'02', 'mode_store_and_forward' :'03', 'type_default' :'00', 'type_delivery_receipt' :'04', 'type_delivery_ack' :'08', 'type_0011' :'0a', 'type_user_ack' :'10', 'type_0101' :'14', 'type_conversation_abort' :'18', 'type_0111' :'1a', 'type_intermed_deliv_notif' :'20', 'type_1001' :'24', 'type_1010' :'28', 'type_1011' :'2a', 'type_1100' :'30', 'type_1101' :'34', 'type_1110' :'38', 'type_1111' :'3a', 'feature_none' :'00', 'feature_UDHI' :'40', 'feature_reply_path' :'80', 'feature_UDHI_and_reply_path':'c0' } # Registered Delivery bits - SMPP v3.4, section 5.2.17, page 124 maps['registered_delivery_bits'] = { 'receipt_mask' :'03', 'ack_mask' :'0c', 'intermed_notif_mask' :'80', 'receipt_none' :'00', 'receipt_always' :'01', 'receipt_on_fail' :'02', 'receipt_res' :'03', 'ack_none' :'00', 'ack_delivery' :'04', 'ack_user' :'08', 'ack_delivery_and_user':'0c', 'intermed_notif_none' :'00', 'intermed_notif' :'10' } # submit_multi dest_flag constants - SMPP v3.4, section 5.2.25, page 129 #maps['dest_flag_by_name'] = { #'SME Address' :1, #'Distribution List Name':2 #} # Message State codes returned in query_sm_resp PDUs - SMPP v3.4, section 5.2.28, table 5-6, page 130 maps['message_state_by_name'] = { 'ENROUTE' :1, 'DELIVERED' :2, 'EXPIRED' :3, 'DELETED' :4, 'UNDELIVERABLE':5, 'ACCEPTED' :6, 'UNKNOWN' :7, 'REJECTED' :8 } # Facility Code bits for SMPP v4 maps['facility_code_bits'] = { 'GF_PVCY' :'00000001', 'GF_SUBADDR':'00000002', 'NF_CC' :'00080000', 'NF_PDC' :'00010000', 'NF_IS136' :'00020000', 'NF_IS95A' :'00040000' } # Optional Parameter Tags - SMPP v3.4, section 5.3.2, Table 5-7, page 132-133 optional_parameter_tag_by_hex = { '0005':{'hex':'0005', 'name':'dest_addr_subunit', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.1, page 134 '0006':{'hex':'0006', 'name':'dest_network_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.3, page 135 '0007':{'hex':'0007', 'name':'dest_bearer_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.5, page 136 '0008':{'hex':'0008', 'name':'dest_telematics_id', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.7, page 137 '000d':{'hex':'000d', 'name':'source_addr_subunit', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.2, page 134 '000e':{'hex':'000e', 'name':'source_network_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.4, page 135 '000f':{'hex':'000f', 'name':'source_bearer_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.6, page 136 '0010':{'hex':'0010', 'name':'source_telematics_id', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.8, page 137 '0017':{'hex':'0017', 'name':'qos_time_to_live', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.9, page 138 '0019':{'hex':'0019', 'name':'payload_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.10, page 138 '001d':{'hex':'001d', 'name':'additional_status_info_text', 'type':'string', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.11, page 139 '001e':{'hex':'001e', 'name':'receipted_message_id', 'type':'string', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.12, page 139 '0030':{'hex':'0030', 'name':'ms_msg_wait_facilities', 'type':'bitmask', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.13, page 140 '0101':{'hex':'0101', 'name':'PVCY_AuthenticationStr', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 58-62 '0201':{'hex':'0201', 'name':'privacy_indicator', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.14, page 141 '0202':{'hex':'0202', 'name':'source_subaddress', 'type':'hex', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.15, page 142 '0203':{'hex':'0203', 'name':'dest_subaddress', 'type':'hex', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.16, page 143 '0204':{'hex':'0204', 'name':'user_message_reference', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.17, page 143 '0205':{'hex':'0205', 'name':'user_response_code', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.18, page 144 '020a':{'hex':'020a', 'name':'source_port', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.20, page 145 '020b':{'hex':'020b', 'name':'destination_port', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.21, page 145 '020c':{'hex':'020c', 'name':'sar_msg_ref_num', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.22, page 146 '020d':{'hex':'020d', 'name':'language_indicator', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.19, page 144 '020e':{'hex':'020e', 'name':'sar_total_segments', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.23, page 147 '020f':{'hex':'020f', 'name':'sar_segment_seqnum', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.24, page 147 '0210':{'hex':'0210', 'name':'sc_interface_version', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.25, page 148 '0301':{'hex':'0301', 'name':'CC_CBN', 'type':None, 'tech':'V4'}, # v4 page 70 '0302':{'hex':'0302', 'name':'callback_num_pres_ind', 'type':'bitmask', 'tech':'TDMA'}, # SMPP v3.4, section 5.3.2.37, page 156 '0303':{'hex':'0303', 'name':'callback_num_atag', 'type':'hex', 'tech':'TDMA'}, # SMPP v3.4, section 5.3.2.38, page 157 '0304':{'hex':'0304', 'name':'number_of_messages', 'type':'integer', 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.39, page 158 '0381':{'hex':'0381', 'name':'callback_num', 'type':'hex', 'tech':'CDMA, TDMA, GSM, iDEN'}, # SMPP v3.4, section 5.3.2.36, page 155 '0420':{'hex':'0420', 'name':'dpf_result', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.28, page 149 '0421':{'hex':'0421', 'name':'set_dpf', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.29, page 150 '0422':{'hex':'0422', 'name':'ms_availability_status', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.30, page 151 '0423':{'hex':'0423', 'name':'network_error_code', 'type':'hex', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.31, page 152 '0424':{'hex':'0424', 'name':'message_payload', 'type':'hex', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.32, page 153 '0425':{'hex':'0425', 'name':'delivery_failure_reason', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.33, page 153 '0426':{'hex':'0426', 'name':'more_messages_to_send', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.34, page 154 '0427':{'hex':'0427', 'name':'message_state', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.35, page 154 '0428':{'hex':'0428', 'name':'congestion_state', 'type':None, 'tech':'Generic'}, '0501':{'hex':'0501', 'name':'ussd_service_op', 'type':'hex', 'tech':'GSM (USSD)'}, # SMPP v3.4, section 5.3.2.44, page 161 '0600':{'hex':'0600', 'name':'broadcast_channel_indicator', 'type':None, 'tech':'GSM'}, '0601':{'hex':'0601', 'name':'broadcast_content_type', 'type':None, 'tech':'CDMA, TDMA, GSM'}, '0602':{'hex':'0602', 'name':'broadcast_content_type_info', 'type':None, 'tech':'CDMA, TDMA'}, '0603':{'hex':'0603', 'name':'broadcast_message_class', 'type':None, 'tech':'GSM'}, '0604':{'hex':'0604', 'name':'broadcast_rep_num', 'type':None, 'tech':'GSM'}, '0605':{'hex':'0605', 'name':'broadcast_frequency_interval', 'type':None, 'tech':'CDMA, TDMA, GSM'}, '0606':{'hex':'0606', 'name':'broadcast_area_identifier', 'type':None, 'tech':'CDMA, TDMA, GSM'}, '0607':{'hex':'0607', 'name':'broadcast_error_status', 'type':None, 'tech':'CDMA, TDMA, GSM'}, '0608':{'hex':'0608', 'name':'broadcast_area_success', 'type':None, 'tech':'GSM'}, '0609':{'hex':'0609', 'name':'broadcast_end_time', 'type':None, 'tech':'CDMA, TDMA, GSM'}, '060a':{'hex':'060a', 'name':'broadcast_service_group', 'type':None, 'tech':'CDMA, TDMA'}, '060b':{'hex':'060b', 'name':'billing_identification', 'type':None, 'tech':'Generic'}, '060d':{'hex':'060d', 'name':'source_network_id', 'type':None, 'tech':'Generic'}, '060e':{'hex':'060e', 'name':'dest_network_id', 'type':None, 'tech':'Generic'}, '060f':{'hex':'060f', 'name':'source_node_id', 'type':None, 'tech':'Generic'}, '0610':{'hex':'0610', 'name':'dest_node_id', 'type':None, 'tech':'Generic'}, '0611':{'hex':'0611', 'name':'dest_addr_np_resolution', 'type':None, 'tech':'CDMA, TDMA (US Only)'}, '0612':{'hex':'0612', 'name':'dest_addr_np_information', 'type':None, 'tech':'CDMA, TDMA (US Only)'}, '0613':{'hex':'0613', 'name':'dest_addr_np_country', 'type':None, 'tech':'CDMA, TDMA (US Only)'}, '1101':{'hex':'1101', 'name':'PDC_MessageClass', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 75 '1102':{'hex':'1102', 'name':'PDC_PresentationOption', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 76 '1103':{'hex':'1103', 'name':'PDC_AlertMechanism', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 76 '1104':{'hex':'1104', 'name':'PDC_Teleservice', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 77 '1105':{'hex':'1105', 'name':'PDC_MultiPartMessage', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 77 '1106':{'hex':'1106', 'name':'PDC_PredefinedMsg', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 78 '1201':{'hex':'1201', 'name':'display_time', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.26, page 148 '1203':{'hex':'1203', 'name':'sms_signal', 'type':'integer', 'tech':'TDMA'}, # SMPP v3.4, section 5.3.2.40, page 158 '1204':{'hex':'1204', 'name':'ms_validity', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.27, page 149 '1304':{'hex':'1304', 'name':'IS95A_AlertOnDelivery', 'type':None, 'tech':'CDMA'}, # v4 page 85 '1306':{'hex':'1306', 'name':'IS95A_LanguageIndicator', 'type':None, 'tech':'CDMA'}, # v4 page 86 '130c':{'hex':'130c', 'name':'alert_on_message_delivery', 'type':None, 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.41, page 159 '1380':{'hex':'1380', 'name':'its_reply_type', 'type':'integer', 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.42, page 159 '1383':{'hex':'1383', 'name':'its_session_info', 'type':'hex', 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.43, page 160 '1402':{'hex':'1402', 'name':'operator_id', 'type':None, 'tech':'vendor extension'}, '1403':{'hex':'1403', 'name':'tariff', 'type':None, 'tech':'Mobile Network Code vendor extension'}, '1450':{'hex':'1450', 'name':'mcc', 'type':None, 'tech':'Mobile Country Code vendor extension'}, '1451':{'hex':'1451', 'name':'mnc', 'type':None, 'tech':'Mobile Network Code vendor extension'} } def optional_parameter_tag_name_by_hex(x): return optional_parameter_tag_by_hex.get(x,{}).get('name') def optional_parameter_tag_type_by_hex(x): return optional_parameter_tag_by_hex.get(x,{}).get('type') optional_parameter_tag_by_name = { 'dest_addr_subunit' :{'hex':'0005', 'name':'dest_addr_subunit', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.1, page 134 'dest_network_type' :{'hex':'0006', 'name':'dest_network_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.3, page 135 'dest_bearer_type' :{'hex':'0007', 'name':'dest_bearer_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.5, page 136 'dest_telematics_id' :{'hex':'0008', 'name':'dest_telematics_id', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.7, page 137 'source_addr_subunit' :{'hex':'000d', 'name':'source_addr_subunit', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.2, page 134 'source_network_type' :{'hex':'000e', 'name':'source_network_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.4, page 135 'source_bearer_type' :{'hex':'000f', 'name':'source_bearer_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.6, page 136 'source_telematics_id' :{'hex':'0010', 'name':'source_telematics_id', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.8, page 137 'qos_time_to_live' :{'hex':'0017', 'name':'qos_time_to_live', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.9, page 138 'payload_type' :{'hex':'0019', 'name':'payload_type', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.10, page 138 'additional_status_info_text' :{'hex':'001d', 'name':'additional_status_info_text', 'type':'string', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.11, page 139 'receipted_message_id' :{'hex':'001e', 'name':'receipted_message_id', 'type':'string', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.12, page 139 'ms_msg_wait_facilities' :{'hex':'0030', 'name':'ms_msg_wait_facilities', 'type':'bitmask', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.13, page 140 'PVCY_AuthenticationStr' :{'hex':'0101', 'name':'PVCY_AuthenticationStr', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 58-62 'privacy_indicator' :{'hex':'0201', 'name':'privacy_indicator', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.14, page 141 'source_subaddress' :{'hex':'0202', 'name':'source_subaddress', 'type':'hex', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.15, page 142 'dest_subaddress' :{'hex':'0203', 'name':'dest_subaddress', 'type':'hex', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.16, page 143 'user_message_reference' :{'hex':'0204', 'name':'user_message_reference', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.17, page 143 'user_response_code' :{'hex':'0205', 'name':'user_response_code', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.18, page 144 'source_port' :{'hex':'020a', 'name':'source_port', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.20, page 145 'destination_port' :{'hex':'020b', 'name':'destination_port', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.21, page 145 'sar_msg_ref_num' :{'hex':'020c', 'name':'sar_msg_ref_num', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.22, page 146 'language_indicator' :{'hex':'020d', 'name':'language_indicator', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.19, page 144 'sar_total_segments' :{'hex':'020e', 'name':'sar_total_segments', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.23, page 147 'sar_segment_seqnum' :{'hex':'020f', 'name':'sar_segment_seqnum', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.24, page 147 'sc_interface_version' :{'hex':'0210', 'name':'sc_interface_version', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.25, page 148 'CC_CBN' :{'hex':'0301', 'name':'CC_CBN', 'type':None, 'tech':'V4'}, # v4 page 70 'callback_num_pres_ind' :{'hex':'0302', 'name':'callback_num_pres_ind', 'type':'bitmask', 'tech':'TDMA'}, # SMPP v3.4, section 5.3.2.37, page 156 'callback_num_atag' :{'hex':'0303', 'name':'callback_num_atag', 'type':'hex', 'tech':'TDMA'}, # SMPP v3.4, section 5.3.2.38, page 157 'number_of_messages' :{'hex':'0304', 'name':'number_of_messages', 'type':'integer', 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.39, page 158 'callback_num' :{'hex':'0381', 'name':'callback_num', 'type':'hex', 'tech':'CDMA, TDMA, GSM, iDEN'}, # SMPP v3.4, section 5.3.2.36, page 155 'dpf_result' :{'hex':'0420', 'name':'dpf_result', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.28, page 149 'set_dpf' :{'hex':'0421', 'name':'set_dpf', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.29, page 150 'ms_availability_status' :{'hex':'0422', 'name':'ms_availability_status', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.30, page 151 'network_error_code' :{'hex':'0423', 'name':'network_error_code', 'type':'hex', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.31, page 152 'message_payload' :{'hex':'0424', 'name':'message_payload', 'type':'hex', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.32, page 153 'delivery_failure_reason' :{'hex':'0425', 'name':'delivery_failure_reason', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.33, page 153 'more_messages_to_send' :{'hex':'0426', 'name':'more_messages_to_send', 'type':'integer', 'tech':'GSM'}, # SMPP v3.4, section 5.3.2.34, page 154 'message_state' :{'hex':'0427', 'name':'message_state', 'type':'integer', 'tech':'Generic'}, # SMPP v3.4, section 5.3.2.35, page 154 'congestion_state' :{'hex':'0428', 'name':'congestion_state', 'type':None, 'tech':'Generic'}, 'ussd_service_op' :{'hex':'0501', 'name':'ussd_service_op', 'type':'hex', 'tech':'GSM (USSD)'}, # SMPP v3.4, section 5.3.2.44, page 161 'broadcast_channel_indicator' :{'hex':'0600', 'name':'broadcast_channel_indicator', 'type':None, 'tech':'GSM'}, 'broadcast_content_type' :{'hex':'0601', 'name':'broadcast_content_type', 'type':None, 'tech':'CDMA, TDMA, GSM'}, 'broadcast_content_type_info' :{'hex':'0602', 'name':'broadcast_content_type_info', 'type':None, 'tech':'CDMA, TDMA'}, 'broadcast_message_class' :{'hex':'0603', 'name':'broadcast_message_class', 'type':None, 'tech':'GSM'}, 'broadcast_rep_num' :{'hex':'0604', 'name':'broadcast_rep_num', 'type':None, 'tech':'GSM'}, 'broadcast_frequency_interval':{'hex':'0605', 'name':'broadcast_frequency_interval', 'type':None, 'tech':'CDMA, TDMA, GSM'}, 'broadcast_area_identifier' :{'hex':'0606', 'name':'broadcast_area_identifier', 'type':None, 'tech':'CDMA, TDMA, GSM'}, 'broadcast_error_status' :{'hex':'0607', 'name':'broadcast_error_status', 'type':None, 'tech':'CDMA, TDMA, GSM'}, 'broadcast_area_success' :{'hex':'0608', 'name':'broadcast_area_success', 'type':None, 'tech':'GSM'}, 'broadcast_end_time' :{'hex':'0609', 'name':'broadcast_end_time', 'type':None, 'tech':'CDMA, TDMA, GSM'}, 'broadcast_service_group' :{'hex':'060a', 'name':'broadcast_service_group', 'type':None, 'tech':'CDMA, TDMA'}, 'billing_identification' :{'hex':'060b', 'name':'billing_identification', 'type':None, 'tech':'Generic'}, 'source_network_id' :{'hex':'060d', 'name':'source_network_id', 'type':None, 'tech':'Generic'}, 'dest_network_id' :{'hex':'060e', 'name':'dest_network_id', 'type':None, 'tech':'Generic'}, 'source_node_id' :{'hex':'060f', 'name':'source_node_id', 'type':None, 'tech':'Generic'}, 'dest_node_id' :{'hex':'0610', 'name':'dest_node_id', 'type':None, 'tech':'Generic'}, 'dest_addr_np_resolution' :{'hex':'0611', 'name':'dest_addr_np_resolution', 'type':None, 'tech':'CDMA, TDMA (US Only)'}, 'dest_addr_np_information' :{'hex':'0612', 'name':'dest_addr_np_information', 'type':None, 'tech':'CDMA, TDMA (US Only)'}, 'dest_addr_np_country' :{'hex':'0613', 'name':'dest_addr_np_country', 'type':None, 'tech':'CDMA, TDMA (US Only)'}, 'PDC_MessageClass' :{'hex':'1101', 'name':'PDC_MessageClass', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 75 'PDC_PresentationOption' :{'hex':'1102', 'name':'PDC_PresentationOption', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 76 'PDC_AlertMechanism' :{'hex':'1103', 'name':'PDC_AlertMechanism', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 76 'PDC_Teleservice' :{'hex':'1104', 'name':'PDC_Teleservice', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 77 'PDC_MultiPartMessage' :{'hex':'1105', 'name':'PDC_MultiPartMessage', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 77 'PDC_PredefinedMsg' :{'hex':'1106', 'name':'PDC_PredefinedMsg', 'type':None, 'tech':'? (J-Phone)'}, # v4 page 78 'display_time' :{'hex':'1201', 'name':'display_time', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.26, page 148 'sms_signal' :{'hex':'1203', 'name':'sms_signal', 'type':'integer', 'tech':'TDMA'}, # SMPP v3.4, section 5.3.2.40, page 158 'ms_validity' :{'hex':'1204', 'name':'ms_validity', 'type':'integer', 'tech':'CDMA, TDMA'}, # SMPP v3.4, section 5.3.2.27, page 149 'IS95A_AlertOnDelivery' :{'hex':'1304', 'name':'IS95A_AlertOnDelivery', 'type':None, 'tech':'CDMA'}, # v4 page 85 'IS95A_LanguageIndicator' :{'hex':'1306', 'name':'IS95A_LanguageIndicator', 'type':None, 'tech':'CDMA'}, # v4 page 86 'alert_on_message_delivery' :{'hex':'130c', 'name':'alert_on_message_delivery', 'type':None, 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.41, page 159 'its_reply_type' :{'hex':'1380', 'name':'its_reply_type', 'type':'integer', 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.42, page 159 'its_session_info' :{'hex':'1383', 'name':'its_session_info', 'type':'hex', 'tech':'CDMA'}, # SMPP v3.4, section 5.3.2.43, page 160 'operator_id' :{'hex':'1402', 'name':'operator_id', 'type':None, 'tech':'vendor extension'}, 'tariff' :{'hex':'1403', 'name':'tariff', 'type':None, 'tech':'Mobile Network Code vendor extension'}, 'mcc' :{'hex':'1450', 'name':'mcc', 'type':None, 'tech':'Mobile Country Code vendor extension'}, 'mnc' :{'hex':'1451', 'name':'mnc', 'type':None, 'tech':'Mobile Network Code vendor extension'} } def optional_parameter_tag_hex_by_name(n): return optional_parameter_tag_by_name.get(n,{}).get('hex') #### Decoding functions ####################################################### def unpack_pdu(pdu_bin): return decode_pdu(binascii.b2a_hex(pdu_bin)) def decode_pdu(pdu_hex): hex_ref = [pdu_hex] pdu = {} pdu['header'] = decode_header(hex_ref) command = pdu['header'].get('command_id', None) if command != None: body = decode_body(command, hex_ref) if len(body) > 0: pdu['body'] = body return pdu def decode_header(hex_ref): pdu_hex = hex_ref[0] header = {} (command_length, command_id, command_status, sequence_number, hex_ref[0]) = \ (pdu_hex[0:8], pdu_hex[8:16], pdu_hex[16:24], pdu_hex[24:32], pdu_hex[32: ]) length = int(command_length, 16) command = command_id_name_by_hex(command_id) status = command_status_name_by_hex(command_status) sequence = int(sequence_number, 16) header = {} header['command_length'] = length header['command_id'] = command header['command_status'] = status header['sequence_number'] = sequence return header def decode_body(command, hex_ref): body = {} if command != None: fields = mandatory_parameter_list_by_command_name(command) mandatory = decode_mandatory_parameters(fields, hex_ref) if len(mandatory) > 0: body['mandatory_parameters'] = mandatory optional = decode_optional_parameters(hex_ref) if len(optional) > 0: body['optional_parameters'] = optional return body def decode_mandatory_parameters(fields, hex_ref): mandatory_parameters = {} if len(hex_ref[0]) > 1: for field in fields: #old = len(hex_ref[0]) data = '' octet = '' count = 0 if field['var'] == True or field['var'] == False: while (len(hex_ref[0]) > 1 and (count < field['min'] or (field['var'] == True and count < field['max']+1 and octet != '00'))): octet = octpop(hex_ref) data += octet count += 1 elif field['type'] in ['string', 'xstring']: count = mandatory_parameters[field['var']] if count == 0: data = None else: for i in range(count): if len(hex_ref[0]) > 1: data += octpop(hex_ref) else: count = mandatory_parameters[field['var']] if field['map'] != None: mandatory_parameters[field['name']] = maps[field['map']+'_by_hex'].get(data, None) if field['map'] == None or mandatory_parameters[field['name']] == None: mandatory_parameters[field['name']] = decode_hex_type(data, field['type'], count, hex_ref) #print field['type'], (old - len(hex_ref[0]))/2, repr(data), field['name'], mandatory_parameters[field['name']] return mandatory_parameters def decode_optional_parameters(hex_ref): optional_parameters = [] hex = hex_ref[0] while len(hex) > 0: (tag_hex, length_hex, rest) = (hex[0:4], hex[4:8], hex[8: ]) tag = optional_parameter_tag_name_by_hex(tag_hex) if tag == None: tag = tag_hex length = int(length_hex, 16) (value_hex, tail) = (rest[0:length*2], rest[length*2: ]) if len(value_hex) == 0: value = None else: value = decode_hex_type(value_hex, optional_parameter_tag_type_by_hex(tag_hex)) hex = tail optional_parameters.append({'tag':tag, 'length':length, 'value':value}) return optional_parameters def decode_hex_type(hex, type, count=0, hex_ref=['']): if hex == None: return hex elif type == 'integer': return int(hex, 16) elif type == 'string': return re.sub('00','',hex).decode('hex') elif type == 'xstring': return hex.decode('hex') elif (type == 'dest_address' or type == 'unsuccess_sme'): list = [] fields = mandatory_parameter_list_by_command_name(type) for i in range(count): item = decode_mandatory_parameters(fields, hex_ref) if item.get('dest_flag', None) == 1: # 'dest_address' only subfields = mandatory_parameter_list_by_command_name('sme_dest_address') rest = decode_mandatory_parameters(subfields, hex_ref) item.update(rest) elif item.get('dest_flag', None) == 2: # 'dest_address' only subfields = mandatory_parameter_list_by_command_name('distribution_list') rest = decode_mandatory_parameters(subfields, hex_ref) item.update(rest) list.append(item) return list else: return hex def octpop(hex_ref): octet = None if len(hex_ref[0]) > 1: (octet, hex_ref[0]) = (hex_ref[0][0:2], hex_ref[0][2: ]) return octet #### Encoding functions ####################################################### def pack_pdu(pdu_obj): return binascii.a2b_hex(encode_pdu(pdu_obj)) def encode_pdu(pdu_obj): header = pdu_obj.get('header', {}) body = pdu_obj.get('body', {}) mandatory = body.get('mandatory_parameters', {}) optional = body.get('optional_parameters', []) body_hex = '' fields = mandatory_parameter_list_by_command_name(header['command_id']) body_hex += encode_mandatory_parameters(mandatory, fields) for opt in optional: body_hex += encode_optional_parameter(opt['tag'], opt['value']) actual_length = 16 + len(body_hex)/2 command_length = '%08x' % actual_length command_id = command_id_hex_by_name(header['command_id']) command_status = command_status_hex_by_name(header['command_status']) sequence_number = '%08x' % header['sequence_number'] pdu_hex = command_length + command_id + command_status + sequence_number + body_hex return pdu_hex def encode_mandatory_parameters(mandatory_obj, fields): mandatory_hex_array = [] index_names = {} index = 0 for field in fields: param = mandatory_obj.get(field['name'], None) param_length = None if param != None or field['min'] > 0: map = None if field['map'] != None: map = maps.get(field['map']+'_by_name', None) if isinstance(param, list): hex_list = [] for item in param: flagfields = mandatory_parameter_list_by_command_name(field['type']) plusfields = [] if item.get('dest_flag', None) == 1: plusfields = mandatory_parameter_list_by_command_name('sme_dest_address') elif item.get('dest_flag', None) == 2: plusfields = mandatory_parameter_list_by_command_name('distribution_list') hex_item = encode_mandatory_parameters(item, flagfields + plusfields) if isinstance(hex_item, str) and len(hex_item) > 0: hex_list.append(hex_item) param_length = len(hex_list) mandatory_hex_array.append(''.join(hex_list)) else: hex_param = encode_param_type( param, field['type'], field['min'], field['max'], map) param_length = len(hex_param)/2 mandatory_hex_array.append(hex_param) index_names[field['name']] = index length_index = index_names.get(field['var'], None) if length_index != None and param_length != None: mandatory_hex_array[length_index] = encode_param_type( param_length, 'integer', len(mandatory_hex_array[length_index])/2) index += 1 return ''.join(mandatory_hex_array) def encode_optional_parameter(tag, value): optional_hex_array = [] tag_hex = optional_parameter_tag_hex_by_name(tag) if tag_hex != None: value_hex = encode_param_type( value, optional_parameter_tag_type_by_hex(tag_hex)) length_hex = '%04x' % (len(value_hex)/2) optional_hex_array.append(tag_hex + length_hex + value_hex) return ''.join(optional_hex_array) -def encode_param_type(param, type, min=0, max=None, map=None): +def encode_param_type(param, type, min=1, max=None, map=None): if param == None: hex = None elif map != None: if type == 'integer' and isinstance(param, int): hex = ('%0'+str(min*2)+'x') % param else: hex = map.get(param, ('%0'+str(min*2)+'x') % 0) elif type == 'integer': hex = ('%0'+str(min*2)+'x') % int(param) print "HEX: ",hex elif type == 'string': hex = param.encode('hex') + '00' elif type == 'xstring': hex = param.encode('hex') elif type == 'bitmask': hex = param elif type == 'hex': hex = param else: hex = None #if hex == None: #hex = '' #if min > 0: #hex = ('%0'+str(min*2)+'x') % 0 #print type, min, max, repr(param), hex, map return hex