Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

ANCHOR SCROLL: chore(docs): add directive to pad heading anchors #9368

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/app/src/.jshintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"browser": true,
"globals": {
"angular": false
}
}
8 changes: 7 additions & 1 deletion docs/app/src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,16 @@ angular.module('docsApp', [
'tutorials',
'versions',
'bootstrap',
'ui.bootstrap.dropdown'
'ui.bootstrap.dropdown',
'heading-offset'
])


.config(['$locationProvider', function($locationProvider) {
$locationProvider.html5Mode(true).hashPrefix('!');
}])

.run(['headingOffset', function(headingOffset) {
// Provide the initial offset for heading anchors
headingOffset.value = '120px';
}]);
87 changes: 87 additions & 0 deletions docs/app/src/heading-offset.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
angular.module('heading-offset', [])

/**
* @ngdoc service
* @description
* The offset to use for heading anchors if not specific offset is given using ngOffSet.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ngOffset (with lowercase s).

* You can set this in a `run` block or update it dynamically based on changing sizes of
* static header.
*/
.value('headingOffset', {value: '0px' })

/**
* @ngdoc directive
* @description
* A directive that matches id attributes on headings (h1, h2, etc) and anchors (a).
* When matched this directive injects a new element that acts as a buffer to ensure that
* when we navigate to the element by id (using a hash on the url) the element appears far
* enough down the page
*
* You can specify the offset on an element by element basis using the `ng-offset` attribute.
* The attribute can be a static value:
*
* ```html
* <h3 id="some-heading" ng-offset="56px">Some Heading</h3>
* ```
*
* or it can be interpolated:
*
* ```html
* <h3 id="some-heading" ng-offset="{{ offset }}">Some Heading</h3>
* ```
*
* If no value is given for `ng-offset` then the directive will use the value given by the
* `headingOffset` service. You can set the value of this at runtime:
*
* ```html
* <h3 id="some-heading">Some Heading</h3>
* ```
*
* ```js
* appModule.run(['headingOffset', function(headingOffset) {
* // Provide the initial offset for heading anchors
* headingOffset.value = '120px';
* }]);
* ```
*
* Be aware that this moves the id to a span below the original element which can play havoc with you
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

...with your...

* CSS if you are relying on ids in your styles (which you shouldn't).
*
*/
.directive('id', ['headingOffset', '$compile', '$anchorScroll', function(headingOffset, $compile, $anchorScroll) {

return {
restrict: 'A',
compile: function(element, attrs) {
if ( /^(h\d+)|(a)$/i.test(element[0].nodeName || attrs.ngOffset ) ) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The regex is wrong. It will match anything either starting with h\d+ or ending with a (e.g. <h1custom-element> or <textarea>).
It should be: /^(h\d+|a)$/i

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And shouldn't it be:

if (/^(h\d+)|(a)$/i.test(element[0].nodeName) || attrs.ngOffset) {

Here again, same as below, attrs.ngOffset might not be the right test, because initially falsy values will go unnoticed.


console.log('processing anchor for', element[0].nodeName, attrs.id);

return function postLink(scope) {

// Create an anchor for this heading
var anchor = $compile('<span style="display: block"></span>')(scope);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just curious: Why a span with display:block and not a plain div ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just copying the idea from other examples. I am not sure if there is any point...
I'll try with a div to see if it makes any difference since that is simpler


// Move the id from the original heading element to the span
anchor.attr('id', attrs.id);
element.removeAttr('id');

// Insert this anchor as the first child of the heading
element.prepend(anchor);

var updateStyle = function(offset) {
anchor.css('margin-top', '-'+offset);
anchor.css('height', offset);
};

// Work out whether we are using a specific offset or getting the global default
if ( attrs.ngOffset ) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a detail, but theoretically we should check if the ng-offset property exists, because we might have an initially falsy value (in order to use the default headingOffset.value), but later on (based on some event) assign a proper value to ngOffset.

E.g.

<h1 id="heading1" ng-offset={{(someCondition) ? '120px' : ''}}></h1>

will end up using headingOffset.value forever (even after someCondition evaluates to true).

Additionally, it might be a good idea to add a check in updateStyle():

var updateStyle = function (offset) {
    offset = offset || headingOffset.value;
    if (offset) {
       ...
    }
};

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My view was that if the ngOffset attribute is ever defined then it should never default to the global headingOffset value. Is that wrong do you think?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The idea is to support having ngOffset evaluate to something under some condition, or evaluate to undefined or null if the condition is not met and let the default headingOffset be used.

E.g. having the following HTML:

<h1 id="heading1" ng-offset="{{weAreOnSmallScreen() ? '0px' : ''}}">Heading 1</h1>

we could account for the following scenario (based on how the docs app is designed):
if we are on a small screen, the header's positioning becomes static (not fixed), so we don't need an offset. So, if weAreOnSmallScreen() evaluates to true, use the value of ngOffset (which is '0px').
If we are on a large screen, the header is fixed and we should use the default offset of headingOffset.value. weAreOnSmallScreen() evaluates to true, attrs.ngOffset evaluates to '' (empty string) and the updateStyle() function understands that it should use the default offset.

This is indeed an implementation choice (i.e. nothing inherenty wrong if we don't support it) and the added flexibility might not be worth the trouble. Up to you :)

scope.$observe('ngOffset', updateStyle);
} else {
scope.$watch(function() { return headingOffset.value; }, updateStyle);
}
};
}
}
};
}]);
11 changes: 11 additions & 0 deletions docs/app/test/.jshintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"browser": true,
"globals": {
"angular": false,
"module": false,
"inject": false,
"describe": false,
"it": false,
"beforeEach": false
}
}
30 changes: 30 additions & 0 deletions docs/app/test/heading-offsetSpec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
describe("heading-offset", function() {
describe("id directive", function() {

var $compile, $scope;

beforeEach(module('heading-offset'));

beforeEach(inject(function($rootScope, _$compile_) {
$scope = $rootScope;
$compile = _$compile_;
}));

it("should inject a span into headings with ids", function() {
var element = $compile('<h1 id="some-id"></h1>')($scope);
var span = element.children();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test is kind of too relaxed, because using children() will only retrieve the element nodes (not text nodes for example). An h element will most probably contain text nodes, so if we want to make sure the anchor is added at the right place we need to account for those as well.

Using .contents() instead, seems more to the point.

(I am not saying the directive is not working as expected; it is. But if it weren't (or if is breaks in the future), this test might still succeed.)

expect(span[0].nodeName).toMatch(/span/i);
expect(element.attr('id')).toBeUndefined();
expect(span.attr('id')).toBe('some-id');
});

it("should inject a span into anchors with ids", function() {
var element = $compile('<a id="some-id"></a>')($scope);
var span = element.children();
expect(span[0].nodeName).toMatch(/span/i);
expect(element.attr('id')).toBeUndefined();
expect(span.attr('id')).toBe('some-id');
});

});
});