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

feat: prettier-action init #56

Merged
merged 8 commits into from
Nov 1, 2024
Merged
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
31 changes: 15 additions & 16 deletions .github/workflows/format.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,27 @@ name: Format

on:
push:
branches: [main]
branches:
- '**' # Any branch

jobs:
format:
runs-on: ubuntu-latest
# Add permissions to allow commits
permissions:
contents: write

steps:
- uses: actions/checkout@v3
- uses: pnpm/[email protected]

- name: Setup Node.js environment
uses: actions/setup-node@v3
- name: Checkout
uses: actions/checkout@v3
with:
node-version: 18

- name: Install dependencies
run: pnpm install --ignore-scripts

- name: Format
run: pnpm run format
# Make sure the actual branch is checked out when running on pull requests
ref: ${{ github.head_ref }}
# This is important to fetch the changes to the previous commit
fetch-depth: 0

- name: Add, Commit and Push
uses: stefanzweifel/git-auto-commit-action@v4
- name: Prettier Action
uses: creyD/prettier_action@v4.3
with:
commit_message: 'Format'
prettier_options: '--config ./.prettierrc --ignore-path .gitignore -w "packages/**/*.{js,ts,json,css,tsx,jsx,md}" "playgrounds/**/*.{js,ts,json,css,tsx,jsx,md}"'
commit_message: "style: auto-format with action"
2 changes: 1 addition & 1 deletion .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ jobs:

steps:
- uses: actions/checkout@v3
- uses: pnpm/action-setup@v2.2.4
- uses: pnpm/action-setup@v4

- name: Setup Node.js environment
uses: actions/setup-node@v3
Expand Down
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,10 @@ pnpm run dev

This will start all the playground in watch mode.


> [!NOTE]
> When code is pushed to any branch, we automatically run a prettier auto-format action that may create a new commit if the code is not properly formatted. To avoid having to pull these auto-format commits, please run `pnpm run format` locally before pushing your changes to the remote branch.

### SolidJS

The project is built using [SolidJS](https://www.solidjs.com/). If you are new to SolidJS, we recommend checking out their [documentation](https://www.solidjs.com/docs) and [tutorials](https://www.solidjs.com/tutorial).
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"build": "turbo run build --filter=./packages/*",
"test": "turbo run test --filter=./packages/*",
"typecheck": "turbo run typecheck --filter=./packages/*",
"build-test": "turbo run build test typecheck --filter=./packages/*",
"build-test": "turbo run build test --filter=./packages/*",
"format": "prettier --ignore-path .gitignore -w \"packages/**/*.{js,ts,json,css,tsx,jsx,md}\" \"playgrounds/**/*.{js,ts,json,css,tsx,jsx,md}\"",
"changeset": "changeset",
"version-packages": "changeset version && pnpm i",
Expand Down
33 changes: 13 additions & 20 deletions packages/shiki-magic-move/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,7 @@ function animate() {
:code="code"
:options="{ duration: 800, stagger: 0.3, lineNumbers: true }"
/>
<button @click="animate">
Animate
</button>
<button @click="animate">Animate</button>
</template>
```

Expand Down Expand Up @@ -162,17 +160,14 @@ import { ShikiMagicMovePrecompiled } from 'shiki-magic-move/vue'
import { ref } from 'vue'

const step = ref(1)
const compiledSteps = [/* Compiled token steps */]
const compiledSteps = [
/* Compiled token steps */
]
</script>

<template>
<ShikiMagicMovePrecompiled
:steps="compiledSteps"
:step="step"
/>
<button @click="step++">
Next
</button>
<ShikiMagicMovePrecompiled :steps="compiledSteps" :step="step" />
<button @click="step++">Next</button>
</template>
```

Expand All @@ -187,19 +182,17 @@ const shiki = await getHighlighter({
langs: ['javascript', 'typescript'],
})

const codeSteps = [
`const hello = 'world'`,
`let hi = 'hello'`,
]
const codeSteps = [`const hello = 'world'`, `let hi = 'hello'`]

const machine = createMagicMoveMachine(
code => codeToKeyedTokens(shiki, code, {
lang: 'ts',
theme: 'nord',
}),
code =>
codeToKeyedTokens(shiki, code, {
lang: 'ts',
theme: 'nord',
}),
{
// options
}
},
)

const compiledSteps = codeSteps.map(code => machine.commit(code).current)
Expand Down
28 changes: 25 additions & 3 deletions packages/shiki-magic-move/build.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,31 @@ export default defineBuildConfig({
},
hooks: {
'rollup:options': async (config, options) => {
options.plugins.unshift(babel({ babelHelpers: 'bundled', include: ['src/**'], exclude: ['src/solid/**', 'src/react/**'], presets: ['@babel/preset-typescript'], extensions: ['.ts', '.js'] }))
options.plugins.unshift(babel({ babelHelpers: 'bundled', include: ['src/solid/**'], presets: ['@babel/preset-typescript', 'solid'], extensions: ['.ts', '.tsx', '.js', '.jsx'] }))
options.plugins.unshift(babel({ babelHelpers: 'bundled', include: ['src/react/**'], presets: ['@babel/preset-typescript', '@babel/preset-react'], extensions: ['.ts', '.tsx', '.js', '.jsx'] }))
options.plugins.unshift(
babel({
babelHelpers: 'bundled',
include: ['src/**'],
exclude: ['src/solid/**', 'src/react/**'],
presets: ['@babel/preset-typescript'],
extensions: ['.ts', '.js'],
}),
)
options.plugins.unshift(
babel({
babelHelpers: 'bundled',
include: ['src/solid/**'],
presets: ['@babel/preset-typescript', 'solid'],
extensions: ['.ts', '.tsx', '.js', '.jsx'],
}),
)
options.plugins.unshift(
babel({
babelHelpers: 'bundled',
include: ['src/react/**'],
presets: ['@babel/preset-typescript', '@babel/preset-react'],
extensions: ['.ts', '.tsx', '.js', '.jsx'],
}),
)
},
'mkdist:done': async () => {
await fs.writeFile('dist/svelte.mjs', 'export * from "./svelte/index.mjs"\n', 'utf-8')
Expand Down
121 changes: 55 additions & 66 deletions packages/shiki-magic-move/src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,14 @@ export function createMagicMoveMachine(
let previous = EMPTY
let current = EMPTY

function commit(code: string, override?: MagicMoveDifferOptions): { current: KeyedTokensInfo, previous: KeyedTokensInfo } {
function commit(
code: string,
override?: MagicMoveDifferOptions,
): { current: KeyedTokensInfo; previous: KeyedTokensInfo } {
previous = current
const mergedOptions = override
? { ...options, ...override }
: options
const newTokens = codeToKeyedTokens(code, mergedOptions.lineNumbers);
({ from: previous, to: current } = syncTokenKeys(previous, newTokens, mergedOptions))
const mergedOptions = override ? { ...options, ...override } : options
const newTokens = codeToKeyedTokens(code, mergedOptions.lineNumbers)
;({ from: previous, to: current } = syncTokenKeys(previous, newTokens, mergedOptions))
return {
current,
previous,
Expand All @@ -44,10 +45,7 @@ export function createMagicMoveMachine(
}
}

export function codeToKeyedTokens<
BundledLangKeys extends string,
BundledThemeKeys extends string,
>(
export function codeToKeyedTokens<BundledLangKeys extends string, BundledThemeKeys extends string>(
highlighter: HighlighterGeneric<BundledLangKeys, BundledThemeKeys>,
code: string,
options: ArgumentsType<HighlighterGeneric<BundledLangKeys, BundledThemeKeys>['codeToTokens']>[1],
Expand Down Expand Up @@ -84,10 +82,8 @@ export function toKeyedTokens(
.flatMap((line, lineIdx): ThemedToken[] => {
firstOffset = line[0]?.offset || lastOffset
const lastEl = line[line.length - 1]
if (!lastEl)
lastOffset += 1
else
lastOffset = lastEl.offset + lastEl.content.length
if (!lastEl) lastOffset += 1
else lastOffset = lastEl.offset + lastEl.content.length
const tokens = [
...line,
{
Expand Down Expand Up @@ -120,23 +116,22 @@ export function toKeyedTokens(
}

function splitWhitespaceTokens(tokens: ThemedToken[][]) {
return tokens.map((line) => {
return line.flatMap((token) => {
if (token.content.match(/^\s+$/))
return token
return tokens.map(line => {
return line.flatMap(token => {
if (token.content.match(/^\s+$/)) return token
// eslint-disable-next-line regexp/no-super-linear-backtracking
const match = token.content.match(/^(\s*)(.*?)(\s*)$/)
if (!match)
return token
if (!match) return token
const [, leading, content, trailing] = match
if (!leading && !trailing)
return token
if (!leading && !trailing) return token

const expanded = [{
...token,
offset: token.offset + leading.length,
content,
}]
const expanded = [
{
...token,
offset: token.offset + leading.length,
content,
},
]
if (leading) {
expanded.unshift({
content: leading,
Expand All @@ -159,10 +154,7 @@ function splitWhitespaceTokens(tokens: ThemedToken[][]) {
*
* The offsets are relative to the token, and should be sorted.
*/
function splitToken(
token: KeyedToken,
offsets: number[],
): KeyedToken[] {
function splitToken(token: KeyedToken, offsets: number[]): KeyedToken[] {
let lastOffset = 0
const key = token.key
let index = 0
Expand Down Expand Up @@ -204,20 +196,19 @@ function splitToken(
* Split 2D tokens array by given breakpoints.
*/
function splitTokens(tokens: KeyedToken[], breakpoints: number[] | Set<number>): KeyedToken[] {
const sorted = Array.from(breakpoints instanceof Set ? breakpoints : new Set(breakpoints))
.sort((a, b) => a - b)
const sorted = Array.from(breakpoints instanceof Set ? breakpoints : new Set(breakpoints)).sort(
(a, b) => a - b,
)

if (!sorted.length)
return tokens
if (!sorted.length) return tokens

return tokens.flatMap((token) => {
return tokens.flatMap(token => {
const breakpointsInToken = sorted
.filter(i => token.offset < i && i < token.offset + token.content.length)
.map(i => i - token.offset)
.sort((a, b) => a - b)

if (!breakpointsInToken.length)
return token
if (!breakpointsInToken.length) return token

return splitToken(token, breakpointsInToken)
})
Expand All @@ -231,49 +222,52 @@ export function syncTokenKeys(
from: KeyedTokensInfo,
to: KeyedTokensInfo,
options: MagicMoveDifferOptions = {},
): { from: KeyedTokensInfo, to: KeyedTokensInfo } {
const {
splitTokens: shouldSplitTokens = false,
enhanceMatching = true,
} = options
): { from: KeyedTokensInfo; to: KeyedTokensInfo } {
const { splitTokens: shouldSplitTokens = false, enhanceMatching = true } = options

// Run the diff and generate matches parts
// In the matched parts, we override the keys with the same key so that the transition group can know they are the same element
const matches = findTextMatches(from.code, to.code, options)
const tokensFrom = shouldSplitTokens
? splitTokens(from.tokens, matches.flatMap(m => m.from))
? splitTokens(
from.tokens,
matches.flatMap(m => m.from),
)
: from.tokens
const tokensTo = shouldSplitTokens
? splitTokens(to.tokens, matches.flatMap(m => m.to))
? splitTokens(
to.tokens,
matches.flatMap(m => m.to),
)
: to.tokens

const matchedKeys = new Set<string>()

matches.forEach((match) => {
const tokensF = tokensFrom.filter(t => t.offset >= match.from[0] && t.offset + t.content.length <= match.from[1])
const tokensT = tokensTo.filter(t => t.offset >= match.to[0] && t.offset + t.content.length <= match.to[1])
matches.forEach(match => {
const tokensF = tokensFrom.filter(
t => t.offset >= match.from[0] && t.offset + t.content.length <= match.from[1],
)
const tokensT = tokensTo.filter(
t => t.offset >= match.to[0] && t.offset + t.content.length <= match.to[1],
)

let idxF = 0
let idxT = 0
while (idxF < tokensF.length && idxT < tokensT.length) {
if (!tokensF[idxF] || !tokensT[idxT])
break
if (!tokensF[idxF] || !tokensT[idxT]) break
if (tokensF[idxF].content === tokensT[idxT].content) {
// assign the key from the first set to the second set
tokensT[idxT].key = tokensF[idxF].key
matchedKeys.add(tokensF[idxF].key)
idxF++
idxT++
}
else if (tokensF[idxF + 1]?.content === tokensT[idxT].content) {
} else if (tokensF[idxF + 1]?.content === tokensT[idxT].content) {
// console.log('Token missing match', tokensF[idxF], undefined)
idxF++
}
else if (tokensF[idxF].content === tokensT[idxT + 1]?.content) {
} else if (tokensF[idxF].content === tokensT[idxT + 1]?.content) {
// console.log('Token missing match', undefined, tokensT[idxT])
idxT++
}
else {
} else {
// console.log('Token missing match', tokensF[idxF], tokensT[idxT])
idxF++
idxT++
Expand All @@ -283,10 +277,8 @@ export function syncTokenKeys(

if (enhanceMatching) {
for (const token of tokensFrom) {
if (matchedKeys.has(token.key))
continue
if (token.content.length < 3 || !token.content.match(/^[\w-]+$/))
continue
if (matchedKeys.has(token.key)) continue
if (token.content.length < 3 || !token.content.match(/^[\w-]+$/)) continue
const matched = tokensTo.find(t => t.content === token.content && !matchedKeys.has(t.key))
if (matched) {
matched.key = token.key
Expand Down Expand Up @@ -327,17 +319,14 @@ export function findTextMatches(
})
aContent += text
bContent += text
}
else if (op === -1) {
} else if (op === -1) {
aContent += text
}
else if (op === 1) {
} else if (op === 1) {
bContent += text
}
}

if (aContent !== a || bContent !== b)
throw new Error('Content mismatch')
if (aContent !== a || bContent !== b) throw new Error('Content mismatch')

return matched
}
Loading
Loading