Stable heading ids

This commit is contained in:
Tom Moor
2018-01-27 00:47:48 -08:00
parent 2b861ea3d5
commit 7647d23804
3 changed files with 21 additions and 7 deletions

View File

@@ -70,8 +70,8 @@ class Contents extends Component {
return (
<Wrapper>
<Sections>
{this.headings.map(heading => {
const slug = headingToSlug(heading);
{this.headings.map((heading, index) => {
const slug = headingToSlug(heading, index);
const active = this.activeHeading === slug;
return (

View File

@@ -1,7 +1,8 @@
// @flow
import React from 'react';
import { Document } from 'slate';
import { Document, Block } from 'slate';
import type { SlateNodeProps } from '../types';
import { List } from 'immutable';
import styled from 'styled-components';
import headingToSlug from '../headingToSlug';
import Placeholder from './Placeholder';
@@ -12,6 +13,15 @@ type Props = SlateNodeProps & {
placeholder: string,
};
function indexInDocument(document, heading) {
const headings = document.nodes.filter((node: Block) => {
if (!node.text) return false;
return node.type.match(/^heading/);
});
return headings.indexOf(heading);
}
function Heading(props: Props) {
const {
parent,
@@ -27,7 +37,10 @@ function Heading(props: Props) {
const parentIsDocument = parent instanceof Document;
const firstHeading = parentIsDocument && parent.nodes.first() === node;
const showPlaceholder = placeholder && firstHeading && !node.text;
const slugish = headingToSlug(node);
const slugish = headingToSlug(
node,
indexInDocument(editor.value.document, node)
);
const showHash = readOnly && !!slugish;
const Component = component;
const emoji = editor.props.emoji || '';

View File

@@ -3,7 +3,8 @@ import { escape } from 'lodash';
import { Node } from 'slate';
import slug from 'slug';
export default function headingToSlug(node: Node) {
const level = node.type.replace('heading', 'h');
return escape(`${level}-${slug(node.text)}-${node.key}`);
export default function headingToSlug(node: Node, index: number = 0) {
const slugified = escape(slug(node.text));
if (index === 0) return slugified;
return `${index}-${slugified}`;
}