Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
3 changes: 2 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@ module.exports = {
'import/no-cycle': 'off',
'import/no-unused-modules': 'off',
'import/no-deprecated': 'off',
// handled by prettier
'max-len': 'off',
// project-specific settings
'max-len': ['error', { code: 100, ignoreComments: true, ignoreStrings: true }],
'no-trailing-spaces': 'error',
'one-var': ['error', 'never'],
'@typescript-eslint/no-unused-vars': ['error', { args: 'none' }],
Expand Down
27 changes: 10 additions & 17 deletions packages/svelte2tsx/src/htmlxtojsx/nodes/action-directive.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,24 @@
import MagicString from 'magic-string';
import { isQuote } from '../utils/node-utils';
import { BaseDirective, BaseNode } from '../../interfaces';
import { handle_subset } from '../utils/node-utils';

/**
* use:xxx={params} ---> {...__sveltets_ensureAction(xxx(__sveltets_mapElementTag('ParentNodeName'),(params)))}
*/
export function handleActionDirective(
htmlx: string,
_htmlx: string,
str: MagicString,
attr: BaseDirective,
parent: BaseNode
): void {
str.overwrite(attr.start, attr.start + 'use:'.length, '{...__sveltets_ensureAction(');
const subset = handle_subset(str, attr);

if (!attr.expression) {
str.appendLeft(attr.end, `(__sveltets_mapElementTag('${parent.name}')))}`);
return;
}

str.overwrite(
attr.start + `use:${attr.name}`.length,
attr.expression.start,
`(__sveltets_mapElementTag('${parent.name}'),(`
);
str.appendLeft(attr.expression.end, ')))');
const lastChar = htmlx[attr.end - 1];
if (isQuote(lastChar)) {
str.remove(attr.end - 1, attr.end);
if (attr.expression == null) {
const [action] = subset.deconstruct`use:${attr.name}`;
subset.edit`{...__sveltets_ensureAction(${action}(__sveltets_mapElementTag('${parent.name}')))}`;
} else {
// prettier-ignore
const [action, expression] = subset.deconstruct`use:${attr.name}=["']?{${attr.expression}}["']?`;
subset.edit`{...__sveltets_ensureAction(${action}(__sveltets_mapElementTag('${parent.name}'),(${expression})))}`;
}
}
82 changes: 82 additions & 0 deletions packages/svelte2tsx/src/htmlxtojsx/utils/node-utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Node, walk } from 'estree-walker';
import MagicString from 'magic-string';
import { BaseNode } from '../../interfaces';
import { surroundWithIgnoreComments } from '../../utils/ignore';

Expand Down Expand Up @@ -211,3 +212,84 @@ export function getIdentifiersInIfExpression(
export function usesLet(node: BaseNode): boolean {
return node.attributes?.some((attr) => attr.type === 'Let');
}

export function handle_subset(str: MagicString, fullnode: BaseNode) {
type Range = {
start: number;
end: number;
};

function print_string(str: string) {
return str.replace(/[\r\n]/g, '↲').replace(/\t/g, '╚');
}

function match_regexp(pattern: string, start: number): Range {
const re = new RegExp(pattern, 'g');
re.lastIndex = start;
const match = re.exec(str.original);
if (!match || match.index !== start) {
throw new Error(`Expected to match /${pattern}/` + at(start));
}
return { start, end: start + match[0].length };
}

function match_string(pattern: string, start: number): Range {
if (str.original.indexOf(pattern, start) !== start) {
throw new Error(`Expected "${pattern}"` + at(start));
}
return { start, end: start + pattern.length };
}

function at(index: number) {
const pre = print_string(str.original.slice(Math.max(0, index - 5), index));
const post = print_string(str.original.slice(index, index + 15));
return `\n ${pre}${post}` + `\n ${pre.replace(/./g, ' ')}^`;
}

function* deconstruct(patterns: TemplateStringsArray, ...nodes: Array<Range | string>) {
let start = fullnode.start;
for (let i = 0; i < patterns.length; i++) {
const pattern = patterns.raw[i];
start = match_regexp(pattern, start).end;
if (i !== patterns.length - 1) {
const node = nodes[i];
if (typeof node === 'string') {
yield match_string(node, start);
start += node.length;
} else {
yield node;
start = node.end;
}
}
}
}

function edit(strings: TemplateStringsArray, ...nodes: Array<Range | string>) {
let start = fullnode.start;
strings = { ...strings };
for (let i = 0; i < nodes.length; i++) {
const next_node = nodes[i];
if (typeof next_node === 'string') {
// @ts-expect-error TemplateStringsArray is readonly
strings[i + 1] = strings[i] + next_node + strings[i + 1];
} else {
if (next_node.start < start) {
const snippet = `${strings.raw[i]}\${<ReorderedNode>}${strings.raw[i + 1]}`;
throw new Error(`Subset Nodes cannot be reordered! (${snippet})`);
}
if (i === 0) {
str.remove(start, next_node.start);
str.prependLeft(next_node.start, strings[i]);
} else {
str.overwrite(start, next_node.start, strings[i]);
}
start = next_node.end;
}
}
const tail = strings[nodes.length];
if (tail) {
str.overwrite(start, fullnode.end + 1, tail + str.original.charAt(fullnode.end));
}
}
return { deconstruct, edit };
}