Stable heading ids
This commit is contained in:
@@ -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 (
|
||||
|
||||
@@ -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 || '';
|
||||
|
||||
@@ -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}`;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user