Skip to content

Commit

Permalink
Fix: Updated with reviews
Browse files Browse the repository at this point in the history
  • Loading branch information
rafaesc committed May 29, 2018
1 parent a1f3903 commit ad5b8b2
Show file tree
Hide file tree
Showing 14 changed files with 196 additions and 50 deletions.
4 changes: 2 additions & 2 deletions src/consts.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,13 @@ export const DisplayModes = Object.freeze({
notFound: 'notFound',
});

export const ExampleMode = Object.freeze({
export const ExampleModes = Object.freeze({
hide: 'hide',
collapse: 'collapse',
expand: 'expand',
});

export const UsageMode = Object.freeze({
export const UsageModes = Object.freeze({
hide: 'hide',
collapse: 'collapse',
expand: 'expand',
Expand Down
13 changes: 8 additions & 5 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import './polyfills';
import './styles';
import ReactDOM from 'react-dom';
import renderStyleguide from './utils/renderStyleguide';
import { getParameterByName, hasInHash } from './utils/handleHash';

// Examples code revision to rerender only code examples (not the whole page) when code changes
// eslint-disable-next-line no-unused-vars
Expand All @@ -11,18 +12,20 @@ let codeRevision = 0;
/** Scrolls to origin when current window location hash points to an isolated view. */
const scrollToOrigin = () => {
const hash = window.location.hash;
if (hash.indexOf('#!/') === 0 || hash.indexOf('#/') === 0) {
if (hasInHash(hash, '#/') || hasInHash(hash, '#!/')) {
const element = document.scrollingElement || document.documentElement; // cross-browsers
/** Extracts the id param of hash */
const idHashParam = getParameterByName(hash, 'id');
let scrollTop = 0;

if (hash.indexOf('?id=') > -1) {
const regex = new RegExp('[\\?&]id=([^&#]*)');
const results = regex.exec(hash);
const idElement = document.getElementById(results[1]);
if (idHashParam) {
// Searches the node with the same id
const idElement = document.getElementById(idHashParam);
if (idElement && idElement.offsetTop) {
scrollTop = idElement.offsetTop;
}
}
/** Scroll to node or page top */
element.scrollTop = scrollTop;
}
};
Expand Down
6 changes: 3 additions & 3 deletions src/rsg-components/Components/Components.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ import React from 'react';
import ReactComponent from '../ReactComponent';
import Components from './Components';
import ComponentsRenderer from './ComponentsRenderer';
import { ExampleMode, UsageMode } from '../../consts';
import { ExampleModes, UsageModes } from '../../consts';

const exampleMode = ExampleMode.collapse;
const usageMode = UsageMode.collapse;
const exampleMode = ExampleModes.collapse;
const usageMode = UsageModes.collapse;
const components = [
{
name: 'Foo',
Expand Down
9 changes: 3 additions & 6 deletions src/rsg-components/NotFound/NotFoundRenderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,10 @@ import PropTypes from 'prop-types';
import Markdown from 'rsg-components/Markdown';
import Styled from 'rsg-components/Styled';

const styles = ({ maxWidth, space }) => ({
const styles = ({ maxWidth }) => ({
root: {
maxWidth,
margin: [[0, 'auto']],
padding: space[4],
},
});

Expand All @@ -16,11 +15,9 @@ export function NotFoundRenderer({ classes }) {
<div className={classes.root}>
<Markdown
text={`
# 404
# Page not found
## Sorry, this page isn't available
The link you followed may be broken, or the page may have been removed
The link you followed may be broken, or the page may have been removed.
`}
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,9 @@ exports[`renderer should render not found message 1`] = `
<div>
<Markdown
text="
# 404
# Page not found
## Sorry, this page isn't available
The link you followed may be broken, or the page may have been removed
The link you followed may be broken, or the page may have been removed.
"
/>
Expand Down
10 changes: 5 additions & 5 deletions src/rsg-components/Playground/Playground.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import Para from 'rsg-components/Para';
import Slot from 'rsg-components/Slot';
import PlaygroundRenderer from 'rsg-components/Playground/PlaygroundRenderer';
import { EXAMPLE_TAB_CODE_EDITOR } from '../slots';
import { DisplayModes, ExampleMode } from '../../consts';
import { DisplayModes, ExampleModes } from '../../consts';

export default class Playground extends Component {
static propTypes = {
Expand All @@ -27,7 +27,7 @@ export default class Playground extends Component {
super(props, context);
const { code, settings, exampleMode } = props;
const { config } = context;
const expandCode = exampleMode === ExampleMode.expand;
const expandCode = exampleMode === ExampleModes.expand;
const activeTab = settings.showcode !== undefined ? settings.showcode : expandCode;

this.state = {
Expand Down Expand Up @@ -67,11 +67,11 @@ export default class Playground extends Component {
const { code, activeTab } = this.state;
const { evalInContext, index, name, settings, exampleMode } = this.props;
const { displayMode } = this.context;
const isSampleHide = exampleMode === ExampleMode.hide;
const hideEditor = settings.noeditor || isSampleHide;
const isExampleHidden = exampleMode === ExampleModes.hide;
const isEditorHidden = settings.noeditor || isExampleHidden;
const preview = <Preview code={code} evalInContext={evalInContext} />;

return hideEditor ? (
return isEditorHidden ? (
<Para>{preview}</Para>
) : (
<PlaygroundRenderer
Expand Down
6 changes: 3 additions & 3 deletions src/rsg-components/ReactComponent/ReactComponent.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import Markdown from 'rsg-components/Markdown';
import Slot from 'rsg-components/Slot';
import ReactComponentRenderer from 'rsg-components/ReactComponent/ReactComponentRenderer';
import { DOCS_TAB_USAGE } from '../slots';
import { DisplayModes, UsageMode } from '../../consts';
import { DisplayModes, UsageModes } from '../../consts';

const ExamplePlaceholder =
process.env.STYLEGUIDIST_ENV !== 'production'
Expand All @@ -33,7 +33,7 @@ export default class ReactComponent extends Component {
this.handleTabChange = this.handleTabChange.bind(this);

this.state = {
activeTab: usageMode === UsageMode.expand ? DOCS_TAB_USAGE : undefined,
activeTab: usageMode === UsageModes.expand ? DOCS_TAB_USAGE : undefined,
};
}

Expand All @@ -52,7 +52,7 @@ export default class ReactComponent extends Component {
if (!name) {
return null;
}
const showUsage = usageMode !== UsageMode.hide;
const showUsage = usageMode !== UsageModes.hide;

return (
<ReactComponentRenderer
Expand Down
4 changes: 2 additions & 2 deletions src/utils/__tests__/getInfoFromHash.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ describe('getInfoFromHash', () => {
const result = getInfoFromHash('#!/Button');
expect(result).toEqual({
isolate: true,
tokens: ['Button'],
hashArray: ['Button'],
targetName: 'Button',
targetIndex: undefined,
});
Expand All @@ -20,7 +20,7 @@ describe('getInfoFromHash', () => {
const result = getInfoFromHash('#!/Api%20%E7%BB%84%E4%BB%B6');
expect(result).toEqual({
isolate: true,
tokens: ['Api 组件'],
hashArray: ['Api 组件'],
targetName: 'Api 组件',
targetIndex: undefined,
});
Expand Down
2 changes: 1 addition & 1 deletion src/utils/__tests__/getPageTitle.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,6 @@ describe('getPageTitle', () => {
it('should return Error 404 for notFound isolation mode', () => {
const name = 'Section';
const result = getPageTitle([{ name }], baseTitle, 'notFound');
expect(result).toMatch('Error 404 - ' + baseTitle);
expect(result).toMatch('Error 404 - Page not found');
});
});
66 changes: 66 additions & 0 deletions src/utils/__tests__/handleHash.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { hasInHash, getHash, getHashAsArray, getParameterByName } from '../handleHash';

describe('handleHash', () => {
const isolateHash = '#!/';
const routeHash = '#/';

it('hasInHash should return true if has #!/', () => {
const result = hasInHash('#!/FooBar', isolateHash);
expect(result).toBe(true);
});

it('hasInHash should return false if does not have #!/', () => {
const result = hasInHash('#/FooBar', isolateHash);
expect(result).toBe(false);
});

it('hasInHash should return true if has #/', () => {
const result = hasInHash('#/FooBar', routeHash);
expect(result).toBe(true);
});

it('hasInHash should return false if does not have #/', () => {
const result = hasInHash('#!/FooBar', routeHash);
expect(result).toBe(false);
});

it('getHash should return FooBar', () => {
const result = getHash('#/FooBar', routeHash);
expect(result).toBe('FooBar');
});

it('getHash should return FooBar without params', () => {
const result = getHash('#/FooBar?id=Example/Perfect', routeHash);
expect(result).toBe('FooBar');
});

it('getHash should return decode value', () => {
const result = getHash('#!/Api%20%E7%BB%84%E4%BB%B6', isolateHash);
expect(result).toBe('Api 组件');
});

it('getHashAsArray should return array', () => {
const result = getHashAsArray('#!/FooBar/Component', isolateHash);
expect(result).toEqual(['FooBar', 'Component']);
});

it('getHashAsArray should return array without params', () => {
const result = getHashAsArray('#/FooBar/Component?id=Example/Perfect', routeHash);
expect(result).toEqual(['FooBar', 'Component']);
});

it('getParameterByName should return Example when has id param', () => {
const result = getParameterByName('#/FooBar/Component?id=Example', 'id');
expect(result).toBe('Example');
});

it('getParameterByName should return null when do not has params', () => {
const result = getParameterByName('#/FooBar/Component', 'id');
expect(result).toEqual(null);
});

it('getParameterByName should return null when do not has id params', () => {
const result = getParameterByName('#/FooBar/Component?foobar=3', 'id');
expect(result).toEqual(null);
});
});
21 changes: 11 additions & 10 deletions src/utils/getInfoFromHash.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import isNaN from 'lodash/isNaN';
import { hasInHash, getHashAsArray } from './handleHash';

function filterNumbers(item) {
return isNaN(parseInt(item, 10)) && item !== '';
}

/**
* Returns an object containing component/section name and, optionally, an example index
Expand All @@ -10,18 +15,14 @@ import isNaN from 'lodash/isNaN';
* @returns {object}
*/
export default function getInfoFromHash(hash) {
const shouldIsolate = hash.substr(0, 3) === '#!/';
if (shouldIsolate || hash.substr(0, 2) === '#/') {
const path = hash.replace(/\?id=[^]*/, '');
const tokens = path
.substr(shouldIsolate ? 3 : 2)
.split('/')
.map(token => decodeURIComponent(token));
const index = parseInt(tokens[tokens.length - 1], 10);
const shouldIsolate = hasInHash(hash, '#!/');
if (shouldIsolate || hasInHash(hash, '#/')) {
const hashArray = getHashAsArray(hash, shouldIsolate ? '#!/' : '#/');
const index = parseInt(hashArray[hashArray.length - 1], 10);
return {
isolate: shouldIsolate,
tokens: tokens.filter(token => isNaN(parseInt(token, 10)) && token !== ''),
targetName: tokens[0],
hashArray: hashArray.filter(filterNumbers),
targetName: hashArray[0],
targetIndex: isNaN(index) ? undefined : index,
};
}
Expand Down
2 changes: 1 addition & 1 deletion src/utils/getPageTitle.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { DisplayModes } from '../consts';
*/
export default function getPageTitle(sections, baseTitle, displayMode) {
if (displayMode === DisplayModes.notFound) {
return 'Error 404 - ' + baseTitle;
return 'Error 404 - Page not found';
}
if (sections.length) {
if (
Expand Down
24 changes: 16 additions & 8 deletions src/utils/getRouteData.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export default function getRouteData(sections, hash, pagePerSection) {
const infoFromHash = getInfoFromHash(hash, pagePerSection);

// Name of the filtered component/section to show isolated (/#!/Button → Button)
let { targetName, tokens } = infoFromHash;
let { targetName, hashArray } = infoFromHash;

const {
// Index of the fenced block example of the filtered component isolate (/#!/Button/1 → 1)
Expand All @@ -34,22 +34,29 @@ export default function getRouteData(sections, hash, pagePerSection) {
let displayMode = isolate ? DisplayModes.example : DisplayModes.all;

if (pagePerSection && !targetName && sections[0]) {
/** For default takes the first section when pagePerSection enabled */
targetName = sections[0].name;
tokens = [targetName];
hashArray = [targetName];
}

if (targetName) {
let filteredSections;

if (pagePerSection) {
tokens.forEach((tokenName, index) => {
filteredSections = filterComponentsInSectionsByExactName(sections, tokenName, isolate);
// Try to filter each section for depth of each hash ["Documentation", "Files", "Button"]
// When sectionDepth is major of 0, their children should be filtered
hashArray.forEach((hashName, index) => {
// Filter the requested component
filteredSections = filterComponentsInSectionsByExactName(sections, hashName, isolate);
if (filteredSections.length) {
sections = filteredSections;
} else {
let section = findSection(sections, tokenName);
let section = findSection(sections, hashName);
if (section) {
const filterChildren = section.sectionDepth !== 0 && !tokens[index + 1];
if (filterChildren) {
const isLastHashName = !hashArray[index + 1];
const shouldFilterTheirChildren = section.sectionDepth > 0 && isLastHashName;

if (shouldFilterTheirChildren) {
section = {
...section,
sections: [],
Expand All @@ -65,7 +72,8 @@ export default function getRouteData(sections, hash, pagePerSection) {
if (!sections.length) {
displayMode = DisplayModes.notFound;
}
targetName = tokens[tokens.length - 1];
// The targetName takes the last of hashArray
targetName = hashArray[hashArray.length - 1];
} else {
// Filter the requested component if required
filteredSections = filterComponentsInSectionsByExactName(sections, targetName, true);
Expand Down
Loading

0 comments on commit ad5b8b2

Please sign in to comment.