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

Add new diagnostic: deprecated-color-setting-shorthand #366

Merged
merged 3 commits into from
Jun 10, 2022
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@

## [Unreleased]

### Added

- `deprecated-color-setting-shorthand` auto-fixable diagnostic for replacing [deprecated shorthands for setting colors](https://github.com/marp-team/marpit/issues/331) ([#358](https://github.com/marp-team/marp-vscode/issues/358), [#361](https://github.com/marp-team/marp-vscode/pull/366))

## v2.0.1 - 2022-06-06

### Changed
Expand Down
18 changes: 10 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,17 +90,19 @@ Marp for VS Code can detect some basic problems in Marp directives. Diagnostics
<img src="https://raw.githubusercontent.com/marp-team/marp-vscode/main/docs/diagnostics.png" alt="Diagnostics" width="443" />
</p>

| Name | Description | [Quick Fix] |
| :------------------------------ | :------------------------------------------------------------------------------------------------- | :---------: |
| `define-math-global-directive` | Recommend to declare math typesetting library via [`math` global directive][math global directive] | ✅ |
| `deprecated-dollar-prefix` | Check [obsoleted directives prefixed by `$`][dollar-prefix] | ✅ |
| `ignored-math-global-directive` | Report ignored `math` global directive if disabled math by the extension setting | |
| `overloading-global-directive` | Find out overloaded global directives | |
| `unknown-size` | Notify if the specified [size preset] was not defined in a theme | |
| `unknown-theme` | Notify a not recognized theme name | |
| Name | Description | [Quick Fix] |
| :----------------------------------- | :------------------------------------------------------------------------------------------------- | :---------: |
| `define-math-global-directive` | Recommend to declare math typesetting library via [`math` global directive][math global directive] | ✅ |
| `deprecated-color-setting-shorthand` | Check [deprecated shorthands for setting slide colors][color setting shorthand] | ✅ |
| `deprecated-dollar-prefix` | Check [obsoleted directives prefixed by `$`][dollar-prefix] | ✅ |
| `ignored-math-global-directive` | Report ignored `math` global directive if disabled math by the extension setting | |
| `overloading-global-directive` | Find out overloaded global directives | |
| `unknown-size` | Notify if the specified [size preset] was not defined in a theme | |
| `unknown-theme` | Notify a not recognized theme name | |

[quick fix]: https://code.visualstudio.com/docs/editor/refactoring#_code-actions-quick-fixes-and-refactorings
[dollar-prefix]: https://github.com/marp-team/marpit/issues/182
[color setting shorthand]: https://github.com/marp-team/marpit/issues/331
[math global directive]: https://github.com/marp-team/marp-core#math-global-directive
[size preset]: https://github.com/marp-team/marp-core/tree/main/themes#size-name-width-height

Expand Down
14 changes: 14 additions & 0 deletions package-lock.json

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

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,7 @@
"devDependencies": {
"@babel/preset-env": "^7.18.2",
"@marp-team/marp-core": "^3.2.1",
"@types/color-string": "^1.5.2",
"@types/express": "^4.17.13",
"@types/jest": "^27.5.2",
"@types/lodash.debounce": "^4.0.7",
Expand All @@ -269,6 +270,7 @@
"@typescript-eslint/parser": "^5.27.0",
"@vscode/test-web": "^0.0.24",
"abort-controller": "^3.0.0",
"color-string": "^1.9.1",
"dedent": "^0.7.0",
"esbuild": "^0.14.42",
"esbuild-loader": "^2.19.0",
Expand Down
6 changes: 6 additions & 0 deletions src/__mocks__/vscode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@ export class Diagnostic {
) {}
}

export enum DiagnosticTag {
Unnecessary = 1,
Deprecated = 2,
}

export enum DiagnosticSeverity {
Error,
Warning,
Expand Down Expand Up @@ -244,6 +249,7 @@ export const workspace = {
export class WorkspaceEdit {
readonly delete = jest.fn()
readonly insert = jest.fn()
readonly replace = jest.fn()
}

beforeEach(() => {
Expand Down
173 changes: 173 additions & 0 deletions src/diagnostics/deprecated-color-setting-shorthand.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
import {
CancellationToken,
CodeAction,
CodeActionTriggerKind,
CodeActionKind,
Diagnostic,
DiagnosticSeverity,
languages,
Position,
Range,
TextDocument,
WorkspaceEdit,
} from 'vscode'
import { DirectiveParser } from '../directives/parser'
import * as rule from './deprecated-color-setting-shorthand'

jest.mock('vscode')

const doc = (text: string): TextDocument =>
({
getText: () => text,
positionAt: (offset: number) => {
const lines = text.slice(0, offset).split('\n')

// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return new Position(lines.length - 1, lines.pop()!.length)
},
uri: '/test/document',
} as any)

describe('[Diagnostics rule] Deprecated color setting shorthand', () => {
const register = (doc: TextDocument): Diagnostic[] => {
const parser = new DirectiveParser()
const diagnostics: Diagnostic[] = []

rule.register(parser, diagnostics)

parser.parse(doc)
return diagnostics
}

describe('#register', () => {
it('does not add diagnostics, to the image syntax not for setting colors', () => {
expect(register(doc('![](/image.jpg)'))).toHaveLength(0)
expect(register(doc('![unknown](blue)'))).toHaveLength(0)
})

it('adds diagnostics to warn deprecated directives when used shorthand syntax for setting color', () => {
// Text
const [$text] = register(doc('![](red)'))

expect($text).toBeInstanceOf(Diagnostic)
expect($text.code).toBe(rule.code)
expect($text.source).toBe('marp-vscode')
expect($text.severity).toBe(DiagnosticSeverity.Warning)
expect($text.range).toStrictEqual(
new Range(new Position(0, 0), new Position(0, 8))
)

// Background
const [$bg] = register(doc('![bg](currentColor)'))

expect($bg).toBeInstanceOf(Diagnostic)
expect($bg.code).toBe(rule.code)
expect($bg.source).toBe('marp-vscode')
expect($bg.severity).toBe(DiagnosticSeverity.Warning)
expect($bg.range).toStrictEqual(
new Range(new Position(0, 0), new Position(0, 19))
)

// Multiple syntaxes in inline
const [$inlineText, $inlineBg] = register(
doc('![](#abc)![bg](rgb(0,0,0))')
)

expect($inlineText).toBeInstanceOf(Diagnostic)
expect($inlineText.code).toBe(rule.code)
expect($inlineText.range).toStrictEqual(
new Range(new Position(0, 0), new Position(0, 9))
)
expect($inlineBg).toBeInstanceOf(Diagnostic)
expect($inlineBg.code).toBe(rule.code)
expect($inlineBg.range).toStrictEqual(
new Range(new Position(0, 9), new Position(0, 26))
)
})
})

describe('#subscribe', () => {
it('subscribes registered DeprecatedColorSettingShorthand code action provider', () => {
const subscriptions: any[] = []
rule.subscribe(subscriptions)

expect(languages.registerCodeActionsProvider).toHaveBeenCalledWith(
'markdown',
expect.any(rule.DeprecatedColorSettingShorthand),
{
providedCodeActionKinds: [CodeActionKind.QuickFix],
}
)
})
})

describe('DeprecatedColorSettingShorthand code action', () => {
describe('#provideCodeActions', () => {
const dummyRange = new Range(new Position(0, 0), new Position(0, 0))
const dummyToken = {} as CancellationToken

it('returns created code actions for corresponding diagnostics', () => {
const document = doc('![](#012abc)\n![bg](rgba(1,2,3,0.5))')
const diagnostics = register(document)
const codeActions =
new rule.DeprecatedColorSettingShorthand().provideCodeActions(
document,
dummyRange,
{
diagnostics,
triggerKind: CodeActionTriggerKind.Invoke,
only: undefined,
},
dummyToken
)

expect(codeActions).toHaveLength(2)
expect(codeActions?.[0]).toBeInstanceOf(CodeAction)
expect(codeActions?.[1]).toBeInstanceOf(CodeAction)

// Quick fix action
const textAction: CodeAction = codeActions?.[0]
expect(textAction.kind).toBe(CodeActionKind.QuickFix)
expect(textAction.diagnostics).toStrictEqual([diagnostics[0]])
expect(textAction.edit).toBeInstanceOf(WorkspaceEdit)
expect(textAction.isPreferred).toBe(true)
expect(textAction.edit?.replace).toHaveBeenCalledTimes(1)
expect(textAction.edit?.replace).toHaveBeenCalledWith(
document.uri,
new Range(new Position(0, 0), new Position(0, 12)),
'<!-- _color: "#012abc" -->'
)

const bgAction: CodeAction = codeActions?.[1]
expect(bgAction.kind).toBe(CodeActionKind.QuickFix)
expect(bgAction.diagnostics).toStrictEqual([diagnostics[1]])
expect(bgAction.edit).toBeInstanceOf(WorkspaceEdit)
expect(bgAction.isPreferred).toBe(true)
expect(bgAction.edit?.replace).toHaveBeenCalledTimes(1)
expect(bgAction.edit?.replace).toHaveBeenCalledWith(
document.uri,
new Range(new Position(1, 0), new Position(1, 22)),
'<!-- _backgroundColor: "rgba(1,2,3,0.5)" -->'
)
})

it('does not create code actions when corresponding diagnostics have not passed', () => {
const document = doc('![unknown](red)')
const diagnostics = register(document)
const codeActions =
new rule.DeprecatedColorSettingShorthand().provideCodeActions(
document,
dummyRange,
{
diagnostics,
triggerKind: CodeActionTriggerKind.Invoke,
only: undefined,
},
dummyToken
)

expect(codeActions).toHaveLength(0)
})
})
})
})
102 changes: 102 additions & 0 deletions src/diagnostics/deprecated-color-setting-shorthand.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import colorString from 'color-string'
import {
CodeAction,
CodeActionKind,
CodeActionProvider,
Diagnostic,
DiagnosticSeverity,
DiagnosticTag,
Disposable,
TextDocument,
WorkspaceEdit,
languages,
} from 'vscode'
import { DirectiveParser } from '../directives/parser'

const diagnosticMeta: unique symbol = Symbol()

interface DeprecatedColorSettingShorthandDiagnostic extends Diagnostic {
[diagnosticMeta]: { replacement: string }
}

export const code = 'deprecated-color-setting-shorthand'

export function register(
directiveParser: DirectiveParser,
diagnostics: Diagnostic[]
) {
directiveParser.on('image', ({ alt, range, url }) => {
const directive = (() => {
if (alt === '') return 'color' as const
if (alt === 'bg') return 'backgroundColor' as const
return undefined
})()
if (directive === undefined) return

if (colorString.get(url) || url.toLowerCase() === 'currentcolor') {
const diagnostic = Object.assign(
new Diagnostic(
range,
`Shorthand for setting colors via Markdown image syntax is deprecated, and will be removed in future. Please replace to the scoped local direcitve <!-- _${directive}: "${url}" -->, or consider to use the scoped style.`,
DiagnosticSeverity.Warning
),
{
source: 'marp-vscode',
code,
tags: [DiagnosticTag.Deprecated],
[diagnosticMeta]: {
replacement: `<!-- _${directive}: "${url}" -->`,
},
}
)

diagnostics.push(diagnostic)
}
})
}

export class DeprecatedColorSettingShorthand implements CodeActionProvider {
static readonly providedCodeActionKinds = [CodeActionKind.QuickFix]

readonly provideCodeActions: CodeActionProvider['provideCodeActions'] = (
doc,
_,
context
) =>
context.diagnostics
.filter(
(d): d is DeprecatedColorSettingShorthandDiagnostic =>
d.source === 'marp-vscode' && d.code === code && d[diagnosticMeta]
)
.map((d) => this.createCodeAction(d, doc))

private createCodeAction(
diag: DeprecatedColorSettingShorthandDiagnostic,
doc: TextDocument
): CodeAction {
const act = new CodeAction(
`Replace to the scoped local direcitve: ${diag[diagnosticMeta].replacement}`,
CodeActionKind.QuickFix
)

act.diagnostics = [diag]
act.edit = new WorkspaceEdit()
act.edit.replace(doc.uri, diag.range, diag[diagnosticMeta].replacement)
act.isPreferred = true

return act
}
}

export function subscribe(subscriptions: Disposable[]) {
subscriptions.push(
languages.registerCodeActionsProvider(
'markdown',
new DeprecatedColorSettingShorthand(),
{
providedCodeActionKinds:
DeprecatedColorSettingShorthand.providedCodeActionKinds,
}
)
)
}
Loading