Skip to content

Commit

Permalink
Support custom callback for link press
Browse files Browse the repository at this point in the history
  • Loading branch information
maxkomarychev committed Jun 20, 2019
1 parent 260fad0 commit 96f9bbe
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 7 deletions.
4 changes: 3 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ export default class Markdown extends Component {
static propTypes = {
children: PropTypes.node.isRequired,
renderer: PropTypes.oneOfType([PropTypes.func, PropTypes.instanceOf(AstRenderer)]),
onLinkPress: PropTypes.func,
rules: (props, propName, componentName) => {
let invalidProps = [];
const prop = props[propName];
Expand Down Expand Up @@ -163,7 +164,8 @@ export default class Markdown extends Component {
{
...styles,
...style,
}
},
props.onLinkPress
);
}
}
Expand Down
7 changes: 6 additions & 1 deletion src/lib/AstRenderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,10 @@ export default class AstRenderer {
* @param {Object.<string, function>} renderRules
* @param {any} style
*/
constructor(renderRules, style) {
constructor(renderRules, style, onLinkPress) {
this._renderRules = renderRules;
this._style = style;
this._onLinkPress = onLinkPress;
}

/**
Expand Down Expand Up @@ -56,6 +57,10 @@ export default class AstRenderer {
return this.renderNode(value, parents);
});

if (node.type === "link" || node.type === "blocklink") {
return renderFunction(node, children, parentNodes, this._style, this._onLinkPress);
}

return renderFunction(node, children, parentNodes, this._style);
};

Expand Down
16 changes: 11 additions & 5 deletions src/lib/renderRules.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,17 +51,23 @@ const renderRules = {
);
},
// a
link: (node, children, parent, styles) => {
link: (node, children, parent, styles, onLinkPress) => {
const url = node.attributes.href;
return (
<Text key={node.key} style={styles.link} onPress={() => openUrl(node.attributes.href)}>
<Text key={node.key} style={styles.link} onPress={() => (onLinkPress ? onLinkPress(url) : openUrl(url))}>
{children}
</Text>
);
},
// a with a non text element nested inside
blocklink: (node, children, parent, styles) => {
return (
<TouchableWithoutFeedback key={node.key} onPress={() => openUrl(node.attributes.href)} style={styles.blocklink}>
blocklink: (node, children, parent, styles, onLinkPress) => {
const url = node.attributes.href;
return (
<TouchableWithoutFeedback
key={node.key}
onPress={() => (onLinkPress ? onLinkPress(url) : openUrl(url))}
style={styles.blocklink}
>
<View style={styles.image}>{children}</View>
</TouchableWithoutFeedback>
);
Expand Down

0 comments on commit 96f9bbe

Please sign in to comment.