Skip to content

Commit

Permalink
Add biome
Browse files Browse the repository at this point in the history
  • Loading branch information
mantou132 committed Sep 11, 2024
1 parent 1b61ed8 commit 4bee95a
Show file tree
Hide file tree
Showing 6 changed files with 190 additions and 19 deletions.
1 change: 1 addition & 0 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// See http://go.microsoft.com/fwlink/?LinkId=827846
// for the documentation about the extensions.json format
"recommendations": [
"biomejs.biome",
"tamasfe.even-better-toml",
"rust-lang.rust-analyzer",
"dbaeumer.vscode-eslint",
Expand Down
60 changes: 60 additions & 0 deletions biome.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
{
"$schema": "https://biomejs.dev/schemas/1.8.3/schema.json",
"vcs": {
"enabled": true,
"clientKind": "git",
"useIgnoreFile": true
},
"organizeImports": { "enabled": true },
"formatter": {
"enabled": true,
"formatWithErrors": false,
"indentStyle": "space",
"indentWidth": 2,
"lineEnding": "lf",
"lineWidth": 120,
"attributePosition": "auto"
},
"javascript": {
"formatter": {
"jsxQuoteStyle": "double",
"quoteProperties": "asNeeded",
"trailingCommas": "all",
"semicolons": "always",
"arrowParentheses": "always",
"bracketSpacing": true,
"bracketSameLine": false,
"quoteStyle": "single",
"attributePosition": "auto"
}
},
"overrides": [{ "include": ["*.md"], "formatter": { "lineWidth": 100 } }],
"linter": {
"enabled": true,
"rules": {
"recommended": false,
"complexity": {
"noBannedTypes": "error",
"noUselessTypeConstraint": "error"
},
"correctness": {
"noPrecisionLoss": "error",
"noUnusedVariables": "off",
"useArrayLiterals": "off"
},
"style": {
"noNamespace": "error",
"noNonNullAssertion": "off",
"useAsConstAssertion": "error",
"useBlockStatements": "off"
},
"suspicious": {
"noExplicitAny": "off",
"noExtraNonNullAssertion": "error",
"noFallthroughSwitchClause": "error",
"noMisleadingInstantiator": "error",
"noUnsafeDeclarationMerging": "error"
}
}
}
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"prepare": "husky install && pnpm prepare:build && pnpm prepare:link"
},
"devDependencies": {
"@biomejs/biome": "1.8.3",
"@types/node": "^20.10.0",
"@typescript-eslint/eslint-plugin": "^6.13.1",
"@typescript-eslint/parser": "^6.13.1",
Expand Down
44 changes: 28 additions & 16 deletions packages/gem-book/src/element/elements/pre.ts
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,8 @@ const styles = createCSSSheet(css`
display: none;
}
:host {
display: block;
display: flex;
flex-direction: column;
font-family: ${theme.codeFont};
background: rgb(from ${theme.textColor} r g b / 0.05);
border-radius: ${theme.normalRound};
Expand All @@ -266,7 +267,7 @@ const styles = createCSSSheet(css`
color: rgb(from ${theme.textColor} r g b / 0.5);
}
.container {
height: 100%;
flex-grow: 1;
overflow-y: auto;
scrollbar-width: thin;
position: relative;
Expand Down Expand Up @@ -455,9 +456,9 @@ export class Pre extends GemElement {
this.#ranges = getRanges(this.range, lines);
this.#highlightLineSet = new Set(
this.highlight
? getRanges(this.highlight, lines)
.map(([start, end]) => Array.from({ length: end - start + 1 }, (_, i) => start + i))
.flat()
? getRanges(this.highlight, lines).flatMap(([start, end]) =>
Array.from({ length: end - start + 1 }, (_, i) => start + i),
)
: [],
);
};
Expand Down Expand Up @@ -487,19 +488,31 @@ export class Pre extends GemElement {
this.#onInputHandle();
};

// https://stackoverflow.com/questions/62054839/shadowroot-getselection
#chrome = 'getSelection' in this.shadowRoot!;

#offset = 0;
#onInputHandle = () => {
const selection =
'getSelection' in this.shadowRoot! ? (this.shadowRoot as unknown as Window).getSelection() : getSelection();
if (!selection || selection.focusNode?.nodeType !== Node.TEXT_NODE) return;
let focusNode: Node | null;
let focusOffset = 0;
if (this.#chrome) {
const selection: Selection = (this.shadowRoot as any).getSelection();
focusNode = selection?.focusNode;
focusOffset = selection?.focusOffset;
} else {
const range: Range = (getSelection() as any)?.getComposedRanges(this.shadowRoot)?.at(0);
focusNode = range?.startContainer;
focusOffset = range?.startOffset;
}
if (focusNode?.nodeType !== Node.TEXT_NODE) return;
this.#offset = 0;
const textNodeIterator = document.createNodeIterator(this.#codeRef.element!, NodeFilter.SHOW_TEXT);
while (true) {
const textNode = textNodeIterator.nextNode();
if (textNode && textNode !== selection?.focusNode) {
if (textNode && textNode !== focusNode) {
this.#offset += textNode.nodeValue!.length;
} else {
this.#offset += selection.focusOffset;
this.#offset += focusOffset;
break;
}
}
Expand All @@ -522,6 +535,7 @@ export class Pre extends GemElement {
const range = document.createRange();
range.setStart(textNode, offset);
range.collapse(false);
// TODO: safari not work
sel.removeAllRanges();
sel.addRange(range);
break;
Expand Down Expand Up @@ -556,11 +570,9 @@ export class Pre extends GemElement {
const { parts, lineNumbersParts } = this.#getParts(htmlStr);
this.#codeRef.element.innerHTML = parts.reduce(
(p, c, i) =>
p +
`<span class="code-ignore token comment"> @@ ${lineNumbersParts[i - 1].at(-1)! + 1}-${
`${p}<span class="code-ignore token comment"> @@ ${lineNumbersParts[i - 1].at(-1)! + 1}-${
lineNumbersParts[i].at(0)! - 1
} @@</span>` +
c,
} @@</span>${c}`,
);
this.#setOffset();
};
Expand All @@ -570,10 +582,10 @@ export class Pre extends GemElement {
const ob = new MutationObserver(() => this.update());
ob.observe(this, { childList: true, characterData: true, subtree: true });
const io = new IntersectionObserver((entries) => {
entries.forEach(({ intersectionRatio }) => {
for (const { intersectionRatio } of entries) {
this.#isVisble = intersectionRatio > 0;
this.update();
});
}
});
io.observe(this);
return () => {
Expand Down
12 changes: 9 additions & 3 deletions packages/gem-book/src/plugins/sandpack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -350,14 +350,21 @@ class _GbpSandpackElement extends GemBookPluginElement {
const msg = (await formatMessages(e.errors, { kind: 'error', color: false, terminalWidth: 100 })).join('\n');
code = `console.error(\`${msg.replaceAll('\\', '\\\\').replaceAll('`', '\\`')}\`)`;
}
const loadEventName = '_load_';
const htmlCode = `
${data.files[Object.keys(data.files).find((e) => e.toLowerCase() === 'index.html')!]?.code}
${this.#getErudaResources()
.map((src) => `<script src="${src}"></script>`)
.join('')}
<script type="module">${code}</script>
<script type="module">
addEventListener('DOMContentLoaded', () => parent.postMessage('${loadEventName}', '*'));
${code};
</script>
`;
if (document.head?.firstElementChild?.textContent?.includes('_html_')) {
addEventListener('message', (evt) => {
if (evt.data === loadEventName) this.#state({ status: 'done' });
});
if (!document.head?.firstElementChild?.textContent?.includes('_html_')) {
const url = new URL(`./?${new URLSearchParams({ _html_: encodeURIComponent(htmlCode) })}`, location.href);
iframe.src = url.href;
} else {
Expand All @@ -366,7 +373,6 @@ class _GbpSandpackElement extends GemBookPluginElement {
}
};
compile();
this.#state({ status: 'done' });
return {
listen: (..._rest) => {},
updateSandbox: (sandboxSetup?: SandboxSetup) => {
Expand Down
91 changes: 91 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 4bee95a

Please sign in to comment.