Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: rewrite getAndRemoveConfig(str) function #2472

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from 8 commits
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
24 changes: 12 additions & 12 deletions src/core/render/compiler.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,27 +30,27 @@ const compileMedia = {
url,
};
},
iframe(url, title) {
iframe(url, props) {
return {
html: `<iframe src="${url}" ${
title || 'width=100% height=400'
props || 'width=100% height=400'
}></iframe>`,
};
},
video(url, title) {
video(url, props) {
return {
html: `<video src="${url}" ${title || 'controls'}>Not Support</video>`,
html: `<video src="${url}" ${props || 'controls'}>Not Support</video>`,
};
},
audio(url, title) {
audio(url, props) {
return {
html: `<audio src="${url}" ${title || 'controls'}>Not Support</audio>`,
html: `<audio src="${url}" ${props || 'controls'}>Not Support</audio>`,
};
},
code(url, title) {
code(url, props) {
let lang = url.match(/\.(\w+)$/);

lang = title || (lang && lang[1]);
lang = props || (lang && lang[1]);
if (lang === 'md') {
lang = 'markdown';
}
Expand Down Expand Up @@ -143,9 +143,9 @@ export class Compiler {
* @return {type} Return value description.
*/
compileEmbed(href, title) {
const { str, config } = getAndRemoveConfig(title);
const { config } = getAndRemoveConfig(title);
let embed;
title = str;
const appenedProps = config.type_appened_props;

if (config.include) {
if (!isAbsolutePath(href)) {
Expand All @@ -158,7 +158,7 @@ export class Compiler {

let media;
if (config.type && (media = compileMedia[config.type])) {
embed = media.call(this, href, title);
embed = media.call(this, href, appenedProps);
embed.type = config.type;
} else {
let type = 'code';
Expand All @@ -174,7 +174,7 @@ export class Compiler {
type = 'audio';
}

embed = compileMedia[type].call(this, href, title);
embed = compileMedia[type].call(this, href, appenedProps);
embed.type = type;
}

Expand Down
6 changes: 5 additions & 1 deletion src/core/render/compiler/image.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,11 @@ export const imageCompiler = ({ renderer, contentBase, router }) =>
}

if (config.class) {
attrs.push(`class="${config.class}"`);
let classes = config.class;
if (config.class_appened_props) {
classes = `${config.class} ${config.class_appened_props}`;
}
attrs.push(`class="${classes}"`);
}

if (config.id) {
Expand Down
13 changes: 8 additions & 5 deletions src/core/render/compiler/link.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,12 @@ export const linkCompiler = ({
(renderer.link = function ({ href, title = '', tokens }) {
const attrs = [];
const text = this.parser.parseInline(tokens) || '';
const { str, config } = getAndRemoveConfig(title);
const { config } = getAndRemoveConfig(title);
linkTarget = config.target || linkTarget;
linkRel =
linkTarget === '_blank'
? compilerClass.config.externalLinkRel || 'noopener'
: '';
title = str;

if (
!isAbsolutePath(href) &&
Expand Down Expand Up @@ -54,15 +53,19 @@ export const linkCompiler = ({
}

if (config.class) {
attrs.push(`class="${config.class}"`);
let classes = config.class;
if (config.class_appened_props) {
classes = `${config.class} ${config.class_appened_props}`;
}
attrs.push(`class="${classes}"`);
}

if (config.id) {
attrs.push(`id="${config.id}"`);
}

if (title) {
attrs.push(`title="${title}"`);
if (config.ignore_appened_props) {
attrs.push(`title="${config.ignore_appened_props}"`);
}

return /* html */ `<a href="${href}" ${attrs.join(' ')}>${text}</a>`;
Expand Down
227 changes: 213 additions & 14 deletions src/core/render/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,39 +6,238 @@
* An example of this is ':include :type=code :fragment=demo' is taken and
* then converted to:
*
* Specially the extra values following a key, such as `:propKey=propVal additinalProp1 additinalProp2`
* or `:propKey propVal additinalProp1 additinalProp2`, those additional values will be appended to the key with `_appened_props` suffix
* as the additional props for the key.
* the example above, its result will be `{ propKey: propVal, propKey_appened_props: 'additinalProp1 additinalProp2' }`
*
* ```
* [](_media/example.html ':include :type=code text :fragment=demo :class=foo bar bee')
* {
* include: '',
* type: 'code',
* fragment: 'demo'
* type_appened_props: 'text',
* fragment: 'demo',
* class: 'foo',
* class_appened_props: 'bar bee'
* }
* ```
*
* Any invalid config keys will be logged warning to the console intead of swallow them silently.
*
* @param {string} str The string to parse.
*
* @return {{str: string, config: object}} The original string formatted, and parsed object, { str, config }.
* @return {{str: string, config: object}} The string after parsed the config, and the parsed configs.
*/
export function getAndRemoveConfig(str = '') {
const config = {};

if (str) {
str = str
.replace(/^('|")/, '')
.replace(/('|")$/, '')
.replace(/(?:^|\s):([\w-]+:?)=?([\w-%]+)?/g, (m, key, value) => {
if (key.indexOf(':') === -1) {
config[key] = (value && value.replace(/&quot;/g, '')) || true;
return '';
}

return m;
})
.trim();
return lexer(str.trim());
}

return { str, config };
}

const lexer = function (str) {
const FLAG = ':';
const EQUIL = '=';
const tokens = str.split('');
const configs = {};
let cur = 0;
let startConfigsStringQuote = '';
let startConfigsStringIndex = -1;
let endConfigsStringIndex = -1;

const scanner = function (token) {
if (isAtEnd()) {
return;
}

if (isBlank(token)) {
return;
}
if (token !== FLAG) {
return;
}

let curToken = '';
const start = cur - 1;

// Eat the most close start '/" if it exists.
// The special case is the :id config in heading, which is without quotes wrapped.
if (startConfigsStringIndex === -1) {
const possibleStartQuoteIndex = findPossiableStartQuote(start);
const possibleStartQuote = tokens[possibleStartQuoteIndex];

if (possibleStartQuoteIndex !== -1) {
const possibleEndQuoteIndex = findPossiableEndQuote(
start,
possibleStartQuote,
);

if (!possibleStartQuote) {
return;
}

const possibleEndQuote = tokens[possibleEndQuoteIndex];
if (possibleStartQuote !== possibleEndQuote) {
return;
}
endConfigsStringIndex = possibleEndQuoteIndex;
}

startConfigsStringIndex = possibleStartQuoteIndex;
startConfigsStringQuote = possibleStartQuote;
}

while (
!isBlank(peek()) &&
!(peek() === startConfigsStringQuote) &&
!(peek() === EQUIL) &&
!(peek() === FLAG)
) {
curToken += advance();
}

let match = true;

switch (curToken) {
// Customise ID for headings #Docsify :id=heading .
case 'id':
configs.id = findValuePair();
break;
case 'type':
configs.type = findValuePair();
findAdditionalPropsIfExist('type');
break;
// Ignore to compile link, e.g. :ignore , :ignore title.
case 'ignore':
configs.ignore = true;
findAdditionalPropsIfExist('ignore');
break;
// Include
case 'include':
configs.include = true;
break;
// Embedded code fragments e.g. :fragment=demo'.
case 'fragment':
configs.fragment = findValuePair();
break;
// Disable link :disabled
case 'disabled':
configs.disabled = true;
break;
// Link target config, e.g. target=_blank.
case 'target':
configs.target = findValuePair();
break;
// Image size config, e.g. size=100, size=WIDTHxHEIGHT.
case 'size':
configs.size = findValuePair();
break;
case 'class':
configs.class = findValuePair();
findAdditionalPropsIfExist('class');
break;
case 'no-zoom':
configs['no-zoom'] = true;
break;
default:
// Although it start with FLAG (:), it is an invalid config token for docsify.
match = false;
}

if (match) {
for (let i = start; i < cur; i++) {
tokens[i] = '';
}
}
};

const isAtEnd = function () {
return cur >= tokens.length;
};

const findValuePair = function () {
if (peek() === EQUIL) {
// Skip the EQUIL
advance();
let val = '';
// Find the value until the end of the string or next FLAG
while (!isBlank(peek()) && !peek().match(/['"]/)) {
val += advance();
}

return val.trim().replace(/&quot;/g, '');
}

return '';
};

const findAdditionalPropsIfExist = function (configKey) {
while (isBlank(peek())) {
advance();
if (isAtEnd()) {
break;
}
}

let val = '';
while (!peek().match(/['"]/) && peek() !== FLAG && !isAtEnd()) {
val += advance();
}

val && (configs[configKey + '_appened_props'] = val.trimEnd());
};

const findPossiableStartQuote = function (current) {
for (let i = current - 1; i >= 0; i--) {
if (tokens[i].match(/['"]/)) {
return i;
}
if (!isBlank(tokens[i])) {
return -1;
}
}
return -1;
};

const findPossiableEndQuote = function (current, possibleStartQuote) {
for (let i = current + 1; i < tokens.length; i++) {
if (tokens[i] === possibleStartQuote) {
return i;
}
}
return -1;
};

const peek = function () {
if (isAtEnd()) {
return '';
}
return tokens[cur];
};

const advance = function () {
return tokens[cur++];
};

const isBlank = str => {
return !str || /^\s*$/.test(str);
};

while (!isAtEnd()) {
scanner(advance());
}

for (let i = startConfigsStringIndex; i <= endConfigsStringIndex; i++) {
tokens[i] = '';
}

const content = tokens.join('').trim();
return { str: content, config: configs };
};
/**
* Remove the <a> tag from sidebar when the header with link, details see issue 1069
* @param {string} str The string to deal with.
Expand Down
Loading
Loading