Wrapper for the Prettier code formatter written in Swift

Related tags

Charts Prettier
Overview

Prettier

A wrapper for the Prettier code formatter written in Swift. The package runs the code formatter in Apple's JavaScriptCore. All the necessary JavaScript files are bundled with this package.

Can this package be used in production?

Probably. The package uses stable versions of all dependencies and I intend to use it in one of my upcoming projects. Use it at your own risk though.

Installation

Prettier is distributed using the Swift Package Manager. Install it in your project by adding it as a dependency in your Package.swift manifest or through "Package Dependencies" in your project settings.

let package = Package(
    dependencies: [
        .package(url: "[email protected]:simonbs/Prettier.git", from: "0.1.0")
    ]
)

Usage

To get started with Prettier you must first import the module.

import Prettier

Now you can create an instance of PrettierFormatter.

let formatter = PrettierFormatter(language: .javaScript)

We're passing a language when creating an instance of PrettierFormatter. This is the programming language of the code to format. The package contains all the languages officially supported by the Prettier code formatter which can be built to run in JavaScriptCore. See the list of supported languages below.

After creating an instance of PrettierFormatter, you must prepare the formatter before formatting code.

formatter.prepare()

This prepares the instance by loading the bundled JavaScript files from disk and evaluating them in JavaScriptCore. It is recommended to do this as early as possible so you're ready to format the code later.

With the PrettierFormatter instance prepared you can start formatting code.

// 💩 This is some poorly formatted JavaScript that we'll format.
let script = """
if(hello=="world"){
return"Hello world"
}
"""
// Earlier we have created and prepared our instance of Prettier. We're ready to format the JavaScript code.
let result = formatter.format(script)
switch result {
case .success(let formattedCode):
    print(formattedCode)
    // ✨ Here's our formatted code. Looks great!
    // if (hello == "world") {
    //   return "Hello world";
    // }
case .failure(let error):
    // Perform proper error handling.
    print(error)
}

It's possible to format only a specific range in the input string by calling -format(:limitedTo:).

let result = formatter.format(script, limitedTo: 20 ... 39)
switch result {
case .success(let formattedCode):
    break
case .failure(let error):
    // Perform proper error handling.
    print(error)
}

You can also specify a location to be translated from the unformatted code to the formatted code. This is useful for moving the cursor when developing a text editor.

let result = formatter.format(script, withCursorAtLocation: 38)
switch result {
case .success(let formatResult):
    print(formatResult.formattedString)
    print(formatResult.cursorOffset)
case .failure(let error):
    // Perform proper error handling.
    print(error)
}

Note that the result returned by -format(:withCursorAtLocation:) is different that the result returned from both -format() and -format(:limitedTo:) because this one contains the location in the formatted string.

There are several properties that can be used to tweak the formatted code. These options map 1:1 to options in the JavaScript implementation of Prettier. For more information on the options, please have a look at PrettierFormatter.swift as well as the documentation for the JavaScript implementation of Prettier.

Language Detection

When creating an instance of PrettierFormatter you must specify the language of the code to format. The Language type has initializers to help determine the language of a file given it's filename, file extension or both.

Languages can be detected from the file extension.

let language = Language(fileExtension: "js") // Detected: JavaScript

It can also be detected by specifying a file URL.

let directoryURL = URL(fileURLWithPath: NSTemporaryDirectory())
let fileURL = directoryURL.appendingPathComponent("index.html")
let language = Language(fileURL: fileURL) // Detected: HTML

It also assumes the language of files with common names.

let language = Language(filename: "README") // Detected: Markdown

This logic is based on data stored in the ikatyang/linguist-languages repository.

Supported Languages

This package bundles the Prettier library along with support for the following languages and frameworks:

  • Angular
  • CSS
  • Flow
  • GraphQL
  • HTML
  • Handlebars
  • JSON Stringify
  • JSON With Comments
  • JSON5
  • JSX
  • JavaScript
  • Less
  • Lightning Web Components
  • MDX
  • Markdown
  • PHP
  • PostCSS
  • SCSS
  • TSX
  • TypeScript
  • Vue
  • YAML

Acknowledgements

The package uses the following dependencies.

The language detection is inspired by the one in the JavaScript version of Prettier which depends on data from ikatyang/linguist-languages. Parts of the data stored in that repository was copied into this package.

License

MIT

You might also like...
An interactive line chart written in SwiftUI with many customizations.

LineChartView LineChartView is a Swift Package written in SwiftUI to add a line chart to your app. It has many available customizations and is interac

A simple and beautiful chart lib used in Piner and CoinsMan for iOS(https://github.com/kevinzhow/PNChart) Swift Implementation

PNChart-Swift PNChart(https://github.com/kevinzhow/PNChart) Swift Implementation Installation This isn't on CocoaPods yet, so to install, add this to

 TKRadarChart - A customizable radar chart  in Swift
TKRadarChart - A customizable radar chart in Swift

TKRadarChart A customizable radar chart in Swift Requirements iOS 8.0+ Xcode 9.0 Swift 4.0 Installation CocoaPods You can use CocoaPods to install TKR

Health Sample app using Swift, RxSwift, Anchorage, Charts
Health Sample app using Swift, RxSwift, Anchorage, Charts

HealthSample First run pod install, then build the project and run in your devices or simulators. This project has used RIBs, Swift, RxSwift, Anchorag

Tomato Animated PieChart With Swift
Tomato Animated PieChart With Swift

TomatoAnimatedPieChart Development and compatibility Development platform: iOS Language: Swift UI framework: UIKit Compatibility: iOS 11 or greater De

SwiftyOpenGraph - A swift library that retrieves structured open graph data from webpages.

SwiftyOpenGraph Usage Initialization Base Properties Types Installation License Usage Initialization You use SwiftyOpenGraph by initializing OpenGraph

An overview of the different types of charts you can make with Swift Charts
An overview of the different types of charts you can make with Swift Charts

Swift Charts Examples This repo aims to provide sample code for lots of different chart types for you to use as inspiration for your own projects. We

Using Swift Charts and Voiceover Chart Descriptor to compose music. 🤯
Using Swift Charts and Voiceover Chart Descriptor to compose music. 🤯

Chart de lune 🎵 Using Swift Charts and Voiceover Chart Descriptor to compose music. 🤯 Image source: https://hadikarimi.com/portfolio/claude-debussy-

Date Formatter Pool - is a small utility that creates and stores your Date Formatter for simpler reuse
Date Formatter Pool - is a small utility that creates and stores your Date Formatter for simpler reuse

Date Formatter Pool Date Formatter Pool - is a small utility that creates and stores your Date Formatter for simpler reuse Installation is available i

An Xcode formatter plug-in to format your swift code.
An Xcode formatter plug-in to format your swift code.

Swimat Swimat is an Xcode plug-in to format your Swift code. Preview Installation There are three way to install. Install via homebrew-cask # Homebrew

A Swift Formatter Kit
A Swift Formatter Kit

Format A Swift formatter kit. Simple formatting syntax for decimal numbers, currency, mass, addresses, ordinal numbers and hexadecimal colors. Usage I

Swift Date Formatter

Swift Date Formatter Date Formatter - Sample code on how to use Date Formatter in swift language Author: Denow Cleetus For OSSE Assignment 4 Group 24

🎗 Super lightweight ISO8601 Date Formatter in Swift
🎗 Super lightweight ISO8601 Date Formatter in Swift

ISO8601 ❤️ Support my apps ❤️ Push Hero - pure Swift native macOS application to test push notifications PastePal - Pasteboard, note and shortcut mana

🎗 Super lightweight ISO8601 Date Formatter in Swift
🎗 Super lightweight ISO8601 Date Formatter in Swift

ISO8601 ❤️ Support my apps ❤️ Push Hero - pure Swift native macOS application to test push notifications PastePal - Pasteboard, note and shortcut mana

Jay - Pure-Swift JSON parser & formatter. Fully streamable input and output. Linux & OS X ready.

Pure-Swift JSON parser & formatter. Fully streamable input and output. Linux & OS X ready. Replacement for NSJSONSerialization.

Currency text field formatter available for UIKit and SwiftUI 💶✏️
Currency text field formatter available for UIKit and SwiftUI 💶✏️

CurrencyText provides lightweight libraries for formating text field text as currency, available for both UIKit and SwiftUI. Its main core, the Curren

🪞 Formatter JSON delightfully.

SwiftJSONFormatter 🪞 Formatter JSON delightfully. Highlights Beautify and minify JSON strings. Keep dictionary key order stable. Work with invalid JS

A number formatter that adds K for thousands, M for millions and B for billions

KMBFormatter A number formatter that adds K for thousands, M for millions and B for billions Sample usage: let formatter = KMBFormatter() formatter.st

UITextField realtime currency formatter - format while typing

Objective-C Realtime Currency Formatter An extremely simple Objective-C class for formatting currencies. Ready to work with the UITextFieldDelegate an

Comments
  • Moves resources out of folders

    Moves resources out of folders

    This PR moves all .scm files out of the "js" folders to address an issue where Xcode showed build warnings saying "Couldn't load project at" followed by a path to the "js" folder but then proceeded to build the app successfully.

    I'm unsure why this error occurred. I'm guessing it's a bug in Xcode. However, moving the files seem to fix the issue.

    opened by simonbs 0
  • Moves parsers to separate packages

    Moves parsers to separate packages

    This PR moves the parsers to separate packages. The motivation is to reduce the size of the library in cases where developers don't need all the parsers.

    As a consequence of this the language detection have been removed. Prettier no longer knows of any languages or parsers and as such will provide no assistance in detecting languages.

    opened by simonbs 0
Releases(0.2.1)
  • 0.2.1(Dec 18, 2022)

    What's Changed

    • fix readme by @mingyoung in https://github.com/simonbs/Prettier/pull/3
    • Moves resources out of folders by @simonbs in https://github.com/simonbs/Prettier/pull/4
    • Adds SwiftLint by @simonbs in https://github.com/simonbs/Prettier/pull/5
    • Adds GitHub workflows by @simonbs in https://github.com/simonbs/Prettier/pull/6

    New Contributors

    • @mingyoung made their first contribution in https://github.com/simonbs/Prettier/pull/3

    Full Changelog: https://github.com/simonbs/Prettier/compare/v0.2.0...0.2.1

    Source code(tar.gz)
    Source code(zip)
  • v0.2.0(May 15, 2022)

Owner
Simon Støvring
I tinker with iOS automation and poke at private APIs. Working on Scriptable and Jayson for iOS.
Simon Støvring
🎈 Curated collection of advanced animations that I have developed using (Swift UI for iOS) and (React Native for iOS/Android). Source code is intended to be reused by myself for future projects.

?? Curated collection of advanced animations that I have developed using (Swift UI for iOS) and (React Native for iOS/Android). Source code is intended to be reused by myself for future projects.

Artem Moshnin 5 Apr 3, 2022
Core Plot source code and example applications

Core Plot Cocoa plotting framework for macOS, iOS, and tvOS. Introduction Core Plot is a 2D plotting framework for macOS, iOS, and tvOS. It is highly

Core Plot 2.8k Jan 7, 2023
An adaptive scrollable graph view for iOS to visualise simple discrete datasets. Written in Swift.

ScrollableGraphView Announcements 9-7-2017 - Version 4: Version 4 was released which adds multiple plots, dynamic reloading of values, more reference

Phillip 5.3k Jan 5, 2023
A Fourier Series visualisation written in Swift/SwiftUI

Fourier Series Visualisation in SwiftUI This little app visualises different Fourier series using epicycles and a graph. The number of functions and t

Simon Stiefel 229 Jan 1, 2023
Flower-like chart written in Swift

FlowerChart - custom chart written in Swift Fully vector flower-shaped chart written in Swift Flower-shaped chart written in Swift, this repo is a sam

Alexander Telegin 15 Jun 9, 2021
Light weight charts view generater for iOS. Written in Swift.

# ###Light weight charts view generater for iOS. Written in Swift. Requirements iOS 8.0+ XCode 7.3+ Installation CocoaPods $ pod init specify it in yo

Recruit Holdings. Media Technology Lab 982 Nov 16, 2022
Easy to use Spider (Radar) Chart library for iOS written in Swift.

DDSpiderChart Easy to use Spider (Radar) Chart library for iOS written in Swift. Requirements iOS 8.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ Xcode

Deniz Adalar 82 Nov 14, 2022
Line Chart library for iOS written in Swift

Swift LineChart Usage var lineChart = LineChart() lineChart.addLine([3, 4, 9, 11, 13, 15]) Features Super simple Highly customizable Auto scaling Touc

Mirco Zeiss 601 Nov 15, 2022
FlowerChart - custom chart written in Swift

FlowerChart - custom chart written in Swift Fully vector flower-shaped chart written in Swift Flower-shaped chart written in Swift, this repo is a sam

Alexander Telegin 15 Jun 9, 2021
SwiftUICharts - A simple line and bar charting library that supports accessibility written using SwiftUI.

SwiftUICharts - A simple line and bar charting library that supports accessibility written using SwiftUI.

Majid Jabrayilov 1.4k Jan 9, 2023