1
0
Fork 0

Compare commits

..

3 Commits

Author SHA1 Message Date
Marco Kutscha 5f74fef0ed [Chore] Cleaned up TODO Comments 2024-02-24 13:28:19 +01:00
Marco Kutscha 2db69add1d [Fix] Using local styles instead of fetching them 2024-02-24 13:26:06 +01:00
Marco Kutscha 5c82d48f44 [Feat] Added support for custom highlight themes 2024-02-24 12:58:41 +01:00
107 changed files with 35018 additions and 5442 deletions

View File

@ -1,11 +0,0 @@
[target.x86_64-apple-darwin]
rustflags = [
"-C", "link-arg=-undefined",
"-C", "link-arg=dynamic_lookup",
]
[target.aarch64-apple-darwin]
rustflags = [
"-C", "link-arg=-undefined",
"-C", "link-arg=dynamic_lookup",
]

View File

@ -1,66 +0,0 @@
name: Build
on:
push:
paths:
project.toml
branches:
- main
permissions:
contents: write
jobs:
build:
name: ${{ matrix.platform.os_name }} with rust ${{ matrix.toolchain }}
runs-on: ${{ matrix.platform.os }}
strategy:
fail-fast: false
matrix:
platform:
- os_name: linux-x86_64
os: ubuntu-20.04
target: x86_64-unknown-linux-gnu
origin_dylib_suffix: so
dest_dylib_suffix: so
- os_name: mac-x86_64
os: macOS-latest
target: x86_64-apple-darwin
origin_dylib_suffix: dylib
dest_dylib_suffix: so
- os_name: mac-aarch64
os: macOS-latest
target: aarch64-apple-darwin
origin_dylib_suffix: dylib
dest_dylib_suffix: so
toolchain:
- stable
steps:
- uses: actions/checkout@v3
- name: Build link lib
uses: houseabsolute/actions-rust-cross@v0
with:
command: "build"
working-directory: ./generator
target: ${{ matrix.platform.target }}
toolchain: ${{ matrix.toolchain }}
args: "--release"
- name: Rename dynamic lib
run: cp -rf generator/target/${{ matrix.platform.target }}/release/libgenerator.${{ matrix.platform.origin_dylib_suffix }} lua/${{ matrix.platform.os_name }}generator.${{ matrix.platform.dest_dylib_suffix }}
- name: Commit changes
uses: EndBug/add-and-commit@v7
with:
message: '[Update] generator link library on ${{ matrix.platform.os_name }}'
pull_strategy: 'NO-PULL'
push: false
- name: Push changes
run: |
git pull --rebase
git push

View File

@ -1,19 +0,0 @@
name: Auto Generate Contributor List
on:
push:
branches:
main
permissions:
contents: write
jobs:
generate-contributor-list:
name: Auto generate contributor list
runs-on: ubuntu-latest
steps:
- uses: wow-actions/contributors-list@v1
with:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
svgPath: CONTRIBUTORS.svg

View File

@ -1,21 +0,0 @@
name: Generate TOC
on:
push:
paths:
README.md
branches:
main
permissions:
contents: write
jobs:
generate-toc:
name: TOC Generator
runs-on: ubuntu-latest
steps:
- uses: technote-space/toc-generator@v4
with:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TOC_TITLE: ''

View File

@ -1,13 +1,11 @@
name: Release
on:
workflow_run:
workflows: [build]
types:
- completed
permissions:
contents: write
push:
paths:
project.toml
branches:
- main
jobs:
release:
@ -15,15 +13,20 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
ref: ${{ github.ref }}
- name: Setup python
uses: actions/setup-python@v5
with:
python-version: "3.11"
- name: Replace template
run: python3 scripts/replace-template.py
- name: Commit changes
uses: EndBug/add-and-commit@v9
with:
message: "[Update] apply template"
- name: Read version from project config
id: read_toml
uses: SebRollen/toml-action@v1.0.2
@ -31,21 +34,6 @@ jobs:
file: project.toml
field: project.version
- name: Replace template
run: python3 scripts/replace-template.py
- name: Commit changes
uses: EndBug/add-and-commit@v7
with:
message: '[Release] ${{ steps.read_toml.outputs.value }}'
pull_strategy: 'NO-PULL'
push: false
- name: Push changes
run: |
git pull --rebase
git push
- name: Bump version and push tag
id: tag_version
uses: mathieudutour/github-tag-action@v6.1

2
.gitignore vendored
View File

@ -19,4 +19,4 @@ node_modules
# build
output.css
*.so
snap-server/public

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 3.0 MiB

407
README.md
View File

@ -1,389 +1,51 @@
![image](https://github.com/mistricky/codesnap.nvim/assets/22574136/9fc40afc-cff8-4e18-a04f-e931d32a1fb7)
![image](https://github.com/mistricky/codesnap.nvim/assets/22574136/c8982b8c-c273-4257-9fef-f0f9134fd9a1)
<p align="center">
<img src="https://img.shields.io/badge/For Neovim 0.9+-57A143?logo=neovim&logoColor=fff&style=for-the-badge" alt="Neovim" />
<img src="https://img.shields.io/badge/Neovim-57A143?logo=neovim&logoColor=fff&style=for-the-badge" alt="Neovim" />
<img src="https://img.shields.io/badge/Made%20With%20Lua-2C2D72?logo=lua&logoColor=fff&style=for-the-badge" alt="made with lua" >
<img src="https://img.shields.io/github/actions/workflow/status/mistricky/codesnap.nvim/release.yml?style=for-the-badge&label=release" alt="release action status" />
<img src="https://img.shields.io/github/actions/workflow/status/mistricky/codesnap.nvim/lint.yml?style=for-the-badge&label=Lint" alt="release action status" />
<a href="https://github.com/mistricky/codesnap.nvim/issues">
<img alt="Issues" src="https://img.shields.io/github/issues/mistricky/codesnap.nvim?style=for-the-badge&logo=github&color=%23ffbd5e">
</a>
<a href="https://github.com/mistricky/codesnap.nvim/blob/main/LICENSE">
<img alt="License" src="https://img.shields.io/github/license/mistricky/codesnap.nvim?style=for-the-badge&logo=github&color=%235ef1ff">
</a>
<a href="https://github.com/mistricky/codesnap.nvim/stars">
<img alt="stars" src="https://img.shields.io/github/stars/mistricky/codesnap.nvim?style=for-the-badge&logo=github&color=%23bd5eff">
</a>
<img src="https://img.shields.io/badge/Made%20With%20Lua-2C2D72?logo=lua&logoColor=fff&style=for-the-badge" alt="made with lua" >
<img src="https://img.shields.io/badge/Written%20in%20Rust-DEA584?logo=rust&logoColor=fff&style=for-the-badge" alt="written in rust" >
<a href="https://dotfyle.com/plugins/mistricky/codesnap.nvim">
<img src="https://dotfyle.com/plugins/mistricky/codesnap.nvim/shield?style=for-the-badge" />
</a>
</p>
<h1 align="center">CodeSnap.nvim</h1>
<p align="center">📸 Snapshot plugin with rich features that can make pretty code snapshots for Neovim</p>
<p align="center">📸 Snapshot plugin that can make pretty code snapshots with real-time previews for Neovim</p>
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
- [🚣Migration](#migration)
- [✨Features](#features)
- [Prerequirements](#prerequirements)
- [Install](#install)
- [Compile from source](#compile-from-source)
- [Compile on ARM](#compile-on-arm)
- [Keymappings](#keymappings)
- [Windows Support](#windows-support)
- [Usage](#usage)
- [Copy into the clipboard](#copy-into-the-clipboard)
- [Copy into clipboard on Linux Wayland](#copy-into-clipboard-on-linux-wayland)
- [Save the snapshot](#save-the-snapshot)
- [Highlight code block](#highlight-code-block)
- [How to use](#how-to-use)
- [Take ASCII snapshot](#take-ascii-snapshot)
- [Specify language extension](#specify-language-extension)
- [Breadcrumbs](#breadcrumbs)
- [Show workspace in breadcrumbs](#show-workspace-in-breadcrumbs)
- [Custom path separator](#custom-path-separator)
- [Line number](#line-number)
- [Custom background](#custom-background)
- [Solid color background](#solid-color-background)
- [Customize background padding](#customize-background-padding)
- [Watermark](#watermark)
- [Commands](#commands)
- [Configuration](#configuration)
- [Contribution](#contribution)
- [Contributors](#contributors)
- [License](#license)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## 🚣Migration
If you have installed v0.x before, this chapter will show you what break changes version v1.x introduced.
- The `CodeSnapPreviewOn` command is not supported, if you prefer live-preview, you can pin `CodeSnap.nvim` version to `v0.0.11` to continue using this command.
- The `opacity` and `preview_title` config has been removed from v1.0.0
- The `editor_font_family` was renamed to `code_font_family`
v1.x has a different architecture and better performance than v0.x, and v1.x can generate screenshots directly without an open browser. We recommend you upgrade to v1.x for a better experience.
> [!NOTE]
> This plugin is currently in its early stages and may have some bugs, please feel free to submit issues and PRs.
## ✨Features
- 🔥 Real-time preview
- 🤩 Beautiful code snap template
- 😎 Custom watermark and window style
- 💻 Beautiful Mac-style title bar
- 🤖 Generate snapshots using only a single command
- 🍞 Breadcrumbs for display file path
- 🌊 More beautiful background theme
- 🔢 Support for display line number make sharing code snapshot easier
- 🔆 Highlight specific lines of code
- 🖨️ Generate ASCII art code snapshots
- 💻 Mac style title bar
- 👏 [WIP] Custom template background
- 🤖 [WIP] Generate snapshot just one command
## Prerequirements
- Neovim 0.9.0+
- Rust environment required for compiling codesnap.nvim plugin server source code, visit [Install Rust](https://www.rust-lang.org/tools/install) for more detail.
- NPM required for build preview source code, visit [Install Nodejs](https://nodejs.org/en) for more detail.
## Install
We recommend using [Lazy.nvim](https://github.com/folke/lazy.nvim) to install CodeSnap.nvim, but you can still use another plugin manager you prefer.
**Lazy.nvim**
```lua
{ "mistricky/codesnap.nvim", build = "make" },
```
**Packer**
```lua
use {'mistricky/codesnap.nvim', run = 'make'}
```
**Vim-Plug**
```lua
Plug 'mistricky/codesnap.nvim', { 'do': 'make' }
```
It's worth mentioning that the screenshot feature is implemented by a module called `generator` written in Rust, when `make` the project, the CodeSnap.nvim will mount a precompiled cross-compile `generator` shared file into the plugin that depends on what OS you are using.
We precompiled the following targets:
- x86_64-unknown-linux-gnu
- x86_64-apple-darwin
- aarch64-apple-darwin
If your platform is in the above list, you can just run `make` after the plugin is installed like the above examples do, CodeSnap.nvim will automatically mount the shared file into the plugin. This means you don't need any Rust utils to compile manually from source.
### Compile from source
You need to install Rust development environment before compiling from source, you can refer [Install Rust](https://www.rust-lang.org/tools/install) for more detail.
Please keep in mind, cross-compile to these platforms only helps a portion of users to have out-of-box experience, if your platform is not in the above targets list, you still need to compile from source using `make build_generator`, for instance using Lazy:
```lua
{ "mistricky/codesnap.nvim", build = "make build_generator" },
```
We always recommend you to compile CodeSnap.nvim from `source` instead of using the precompiled shared file, because the correctness and consistency of compiling from source are always higher than cross-compiling.
### Compile on ARM
If you try to compile CodeSnap.nvim on ARM architecture, you may need to install additional dependencies to compile it, thanks @matteocavestri mentioned in https://github.com/mistricky/codesnap.nvim/issues/53#issuecomment-2032088162
```shell
export CC=gcc
sudo dnf install libuv libuv-devel # On RHEL based systems
sudo apt-get install libtool libuv1-dev # On Debian based systems
```
### Keymappings
If you use `Lazy.nvim` as your package manager, here are some examples show you how to configure keymappings for CodeSnap:
```lua
{
"mistricky/codesnap.nvim",
build = "make build_generator",
keys = {
{ "<leader>cc", "<cmd>CodeSnap<cr>", mode = "x", desc = "Save selected code snapshot into clipboard" },
{ "<leader>cs", "<cmd>CodeSnapSave<cr>", mode = "x", desc = "Save selected code snapshot in ~/Pictures" },
},
opts = {
save_path = "~/Pictures",
has_breadcrumbs = true,
bg_theme = "bamboo",
},
}
```
### Windows Support
Unfortunately, CodeSnap does not support Windows yet, but version `v0.0.x` is working fine on Windows. If you want to use CodeSnap on Windows, we recommend you pin the version to `0.0.11` to use CodeSnap, follow to [0.0.11 Document](https://github.com/mistricky/codesnap.nvim/tree/v0.0.11) for more detail.
## Usage
`CodeSnap.nvim` provides the following two ways to take snapshots of currently selected code
For take a screenshot, the `codesnap.nvim` provides a command named `CodeSnapPreviewOn` to open the preview page, and then you can switch to visual mode and select code you want, and finally just click the copy button on the preview page, that's all :)
### Copy into the clipboard
To take a beautiful snapshot use CodeSnap.nvim, you can just use `CodeSnap` command to generate a snapshot of the current selected code, then the `CodeSnap.nvim` will write the snapshot into the clipboard, and you can paste it anywhere you want.
https://github.com/mistricky/codesnap.nvim/assets/22574136/99be72db-57d7-4839-91d0-2a9dfb1901ac
#### Copy into clipboard on Linux Wayland
Copy screenshots directly into the clipboard is cool, however, it doesn't work well on wl-clipboard, because the wl-clipboard can't paste the content which come from exited processes. As Hyprland document say:
> When we copy something on Wayland (using wl-clipboard) and close the application we copied from, the copied data disappears from the clipboard and we cannot paste it anymore. So to fix this problem we can use a program called as wl-clip-persist which will preserve the data in the clipboard after the application is closed.
If you using CodeSnap.nvim on wl-clipboard, you can refer [wl-clip-persist](https://github.com/Linus789/wl-clip-persist), it reads all the clipboard data into memory and then overwrites the clipboard with the data from our memory to persist copied data.
### Save the snapshot
Of course, you can use `CodeSnapSave` command to save the snapshot to path where you defined it in `config.save_path`
```lua
require("codesnap").setup({
-- The save_path must be ends with .png, unless when you specified a directory path,
-- CodeSnap will append an auto-generated filename to the specified directory path
-- For example:
-- save_path = "~/Pictures"
-- parsed: "~/Pictures/CodeSnap_y-m-d_at_h:m:s.png"
-- save_path = "~/Pictures/foo.png"
-- parsed: "~/Pictures/foo.png"
save_path = ...
})
```
https://github.com/mistricky/codesnap.nvim/assets/22574136/69b27e77-3dce-4bc3-8516-89ce636fe02d
### Highlight code block
CodeSnap allows you to take code snapshots with highlights code blocks, we provide two commands for this scenario:
```shell
CodeSnapHighlight # Take code snapshot with highlights code blocks and copy it into the clipboard
CodeSnapSaveHighlight # Take code snapshot with highlights code blocks and save it somewhere
```
#### How to use
For take a code snapshot with highlights code blocks and save it somewhere. First you need to select code which you want to snapshot, then enter the command `CodeSnapSaveHighlight` to open a window show you the selected code which from previous step, now you can select code which you want to highlight, finally press the Enter key, CodeSnap will generate a snapshot with highlight blocks and save it in save_path.
Here is an example video:
https://github.com/mistricky/codesnap.nvim/assets/22574136/bea0bf6c-8fc9-4d09-9cab-4e1e6f47899c
### Take ASCII snapshot
Run `CodeSnapASCII`, CodeSnap will generate a "code snapshot" in ASCII format and then copy it into clipboard automatically, it's really cool and lightweight, if you want to share your code in somewhere like Markdown document, even you can enjoy the code highlighting which provided by Markdown parser. Here is an usage video:
https://github.com/mistricky/codesnap.nvim/assets/22574136/91bc3d96-7dbd-4e1c-9224-95428c7cca48
### Specify language extension
In some scenarios, CodeSnap.nvim cannot auto-detect what language syntax should used to highlight code, for example, shell script can have no extension, they specify interpreters using shebang.
CodeSnap.nvim won't read the whole content of the file, thus cannot detect what language syntax is this, in this case, you can specify extension explicitly, for instance:
```
CodeSnapSave sh
CodeSnap sh
```
## Breadcrumbs
Breadcrumbs are something to display the current snapshot file path, you can open it through config `has_breadcrumbs`:
```lua
require("codesnap").setup({
-- ...
has_breadcrumbs = true
})
```
The breadcrumbs look like:
![image](https://github.com/mistricky/codesnap.nvim/assets/22574136/23274faa-36a9-4d41-88a5-e48c44b4d5bf)
### Show workspace in breadcrumbs
Breadcrumbs hide the workspace name by default, if you want to display workspace in breadcrumbs, you can just set `show_workspace` as true.
```lua
require("codesnap").setup({
-- ...
has_breadcrumbs = true
show_workspace = true
})
```
### Custom path separator
The CodeSnap.nvim uses `/` as the separator of the file path by default, of course, you can specify any symbol you prefer as the custom separator:
```lua
require("codesnap").setup({
-- ...
has_breadcrumbs = true
breadcrumbs_separator = "👉"
})
```
![image](https://github.com/mistricky/codesnap.nvim/assets/22574136/84b80d0f-1467-4bdf-9cbd-aede868f93aa)
## Line number
We also support displaying line number, you can set `has_line_number` to true to display line number.
```lua
require("codesnap").setup({
// ...
has_line_number = true,
})
```
![image](https://github.com/mistricky/codesnap.nvim/assets/22574136/3a5999b1-bb2a-4646-8d69-609be1d28140)
## Custom background
The `CodeSnap.nvim` comes with many beautiful backgrounds preset, you can set any background you like by setting `bg_theme` to its name, just like:
```lua
require("codesnap").setup({
-- The "default" background is one you see at the beginning of the README
bg_theme = "default"
})
```
<table>
<tr>
<th>bamboo</th>
<th>sea</th>
</tr>
<tr>
<td>
<img src="https://github.com/mistricky/codesnap.nvim/assets/22574136/ce3a387b-61a5-42ba-8f71-1b4949f5e148" width="650" />
</td>
<td>
<img src="https://github.com/mistricky/codesnap.nvim/assets/22574136/122790b6-6365-402c-806a-dfc78dabbc06" width="650" />
</td>
</tr>
<tr>
<th>peach</th>
<th>grape</th>
</tr>
<tr>
<td>
<img src="https://github.com/mistricky/codesnap.nvim/assets/22574136/c0ec9dc1-cd8b-463e-9f2d-ab2e1e3a9831" width="650" />
</td>
<td>
<img src="https://github.com/mistricky/codesnap.nvim/assets/22574136/b573786b-70ed-4006-89c7-20bed115c9cc" width="650" />
</td>
</tr>
<tr>
<th>dusk</th>
<th>summer</th>
</tr>
<tr>
<td>
<img src="https://github.com/mistricky/codesnap.nvim/assets/22574136/e3bb5222-542d-4c32-b78b-8cf4695feec9" width="650" />
</td>
<td>
<img src="https://github.com/mistricky/codesnap.nvim/assets/22574136/98ced31a-091b-4ed8-9bd6-bb5b502a7db2" width="650" />
</td>
</tr>
</table>
### Solid color background
If you prefer solid color background, you can set `bg_color` to your preferred color. For example:
```lua
require("codesnap").setup({
-- ...
bg_color = "#535c68"
})
```
![CodeSnap](https://github.com/mistricky/codesnap.nvim/assets/22574136/a600c2e4-4c60-4ec0-b2fc-3b41481048dc)
### Customize background padding
CodeSnap allows you to customize the padding of background using `bg_x_padding`, `bg_y_padding` and `bg_padding`, the default value is:
```lua
require("codesnap").setup({
bg_x_padding = 122,
bg_y_padding = 82,
bg_padding = nil
})
```
If you want to hide background, you can set `bg_padding` to `0` in your config:
```lua
require("codesnap").setup({
-- ...
bg_padding = 0
})
```
## Watermark
Watermark is something that makes screenshots more personalized, but if you don't like watermark just set it as an empty string to hide it.
```lua
require("codesnap").setup({
-- ...
watermark = ""
})
```
https://github.com/mistricky/codesnap.nvim/assets/22574136/5e1a023e-142f-49e8-b24f-707da3728fd5
## Commands
```shell
CodeSnap # Take a snapshot of the currently selected code and copy the snapshot into the clipboard
CodeSnapPreviewOn # Open preview page
CodeSnapSave # Save the snapshot of the currently selected code and save it on the disk
CodeSnapASCII # Take a code snapshot in ASCII format
```
**Lua**
```lua
local codesnap <const> = require("codesnap")
-- Take a snapshot of the currently selected code and copy the snapshot into the clipboard
codesnap.copy_into_clipboard()
-- Save the snapshot of the currently selected code and save it on the disk
codesnap.save_snapshot()
-- The following commands are planned but not implemented yet. (welcome PR :))
CodeSnap # Take a code snap and copy it into the clipboard
```
## Configuration
@ -395,32 +57,15 @@ require("codesnap").setup({...})
There is a default config:
```lua
{
mac_window_bar = true,
title = "CodeSnap.nvim",
code_font_family = "CaskaydiaCove Nerd Font",
watermark_font_family = "Pacifico",
watermark = "CodeSnap.nvim",
bg_theme = "default",
breadcrumbs_separator = "/",
has_breadcrumbs = false,
has_line_number = false,
show_workspace = false,
min_width = 0,
bg_x_padding = 122,
bg_y_padding = 82,
save_path = os.getenv("XDG_PICTURES_DIR") or (os.getenv("HOME").. "/Pictures")
mac_window_bar = true,-- (Optional) MacOS style title bar switch
opacity = true, -- (Optional) The code snap has some opacity by default, set it to false for 100% opacity
watermark = "CodeSnap.nvim", -- (Optional) you can custom your own watermark, but if you don't like it, just set it to ""
preview_title = "CodeSnap.nvim", -- (Optional) preview page title
editor_font_family = "CaskaydiaCove Nerd Font", -- (Optional) preview code font family
watermark_font_family = "Pacifico", -- (Optional) watermark font family
highlight_theme = "atom-one-dark", -- (Optional) theme for code highlights
}
```
## Contribution
CodeSnap.nvim is a project that will be maintained for the long term, and we always accepts new contributors, please feel free to submit PR & issues.
The commit message convention of this project is following [commitlint-wizardoc](https://github.com/wizardoc/commitlint-wizardoc).
### Contributors
Thanks to all contributors for their contributions and works they have done.
<img src="CONTRIBUTORS.svg" />
## License
MIT.

Binary file not shown.

View File

@ -1,560 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>author</key>
<string>Template: Chris Kempson, Scheme: Lalit Magant (http://github.com/tilal6991)</string>
<key>name</key>
<string>Base16 OneDark</string>
<key>semanticClass</key>
<string>theme.base16.onedark</string>
<key>colorSpaceName</key>
<string>sRGB</string>
<key>gutterSettings</key>
<dict>
<key>background</key>
<string>#353b45</string>
<key>divider</key>
<string>#353b45</string>
<key>foreground</key>
<string>#545862</string>
<key>selectionBackground</key>
<string>#3e4451</string>
<key>selectionForeground</key>
<string>#565c64</string>
</dict>
<key>settings</key>
<array>
<dict>
<key>settings</key>
<dict>
<key>background</key>
<string>#282c34</string>
<key>caret</key>
<string>#abb2bf</string>
<key>foreground</key>
<string>#abb2bf</string>
<key>invisibles</key>
<string>#545862</string>
<key>lineHighlight</key>
<string>#54586255</string>
<key>selection</key>
<string>#3e4451</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Text</string>
<key>scope</key>
<string>variable.parameter.function</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#abb2bf</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Comments</string>
<key>scope</key>
<string>comment, punctuation.definition.comment</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#545862</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Punctuation</string>
<key>scope</key>
<string>punctuation.definition.string, punctuation.definition.variable, punctuation.definition.string, punctuation.definition.parameters, punctuation.definition.string, punctuation.definition.array</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#abb2bf</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Delimiters</string>
<key>scope</key>
<string>none</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#abb2bf</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Operators</string>
<key>scope</key>
<string>keyword.operator</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#abb2bf</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Keywords</string>
<key>scope</key>
<string>keyword</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#c678dd</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Variables</string>
<key>scope</key>
<string>variable</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#e06c75</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Functions</string>
<key>scope</key>
<string>entity.name.function, meta.require, support.function.any-method, variable.function, variable.annotation, support.macro</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#61afef</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Labels</string>
<key>scope</key>
<string>entity.name.label</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#be5046</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Classes</string>
<key>scope</key>
<string>support.class, entity.name.class, entity.name.type.class</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#e5c07b</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Classes</string>
<key>scope</key>
<string>meta.class</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#c8ccd4</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Methods</string>
<key>scope</key>
<string>keyword.other.special-method</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#61afef</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Storage</string>
<key>scope</key>
<string>storage</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#c678dd</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Support</string>
<key>scope</key>
<string>support.function</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#56b6c2</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Strings, Inherited Class</string>
<key>scope</key>
<string>string, constant.other.symbol, entity.other.inherited-class</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#98c379</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Integers</string>
<key>scope</key>
<string>constant.numeric</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#d19a66</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Floats</string>
<key>scope</key>
<string>none</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#d19a66</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Boolean</string>
<key>scope</key>
<string>none</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#d19a66</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Constants</string>
<key>scope</key>
<string>constant</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#d19a66</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Tags</string>
<key>scope</key>
<string>entity.name.tag</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#e06c75</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Attributes</string>
<key>scope</key>
<string>entity.other.attribute-name</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#d19a66</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Attribute IDs</string>
<key>scope</key>
<string>entity.other.attribute-name.id, punctuation.definition.entity</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#61afef</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Selector</string>
<key>scope</key>
<string>meta.selector</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#c678dd</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Values</string>
<key>scope</key>
<string>none</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#d19a66</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Headings</string>
<key>scope</key>
<string>markup.heading punctuation.definition.heading, entity.name.section</string>
<key>settings</key>
<dict>
<key>fontStyle</key>
<string></string>
<key>foreground</key>
<string>#61afef</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Units</string>
<key>scope</key>
<string>keyword.other.unit</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#d19a66</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Bold</string>
<key>scope</key>
<string>markup.bold, punctuation.definition.bold</string>
<key>settings</key>
<dict>
<key>fontStyle</key>
<string>bold</string>
<key>foreground</key>
<string>#e5c07b</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Italic</string>
<key>scope</key>
<string>markup.italic, punctuation.definition.italic</string>
<key>settings</key>
<dict>
<key>fontStyle</key>
<string>italic</string>
<key>foreground</key>
<string>#c678dd</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Code</string>
<key>scope</key>
<string>markup.raw.inline</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#98c379</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Link Text</string>
<key>scope</key>
<string>string.other.link, punctuation.definition.string.end.markdown, punctuation.definition.string.begin.markdown</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#e06c75</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Link Url</string>
<key>scope</key>
<string>meta.link</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#d19a66</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Lists</string>
<key>scope</key>
<string>markup.list</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#e06c75</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Quotes</string>
<key>scope</key>
<string>markup.quote</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#d19a66</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Separator</string>
<key>scope</key>
<string>meta.separator</string>
<key>settings</key>
<dict>
<key>background</key>
<string>#3e4451</string>
<key>foreground</key>
<string>#abb2bf</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Inserted</string>
<key>scope</key>
<string>markup.inserted</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#98c379</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Deleted</string>
<key>scope</key>
<string>markup.deleted</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#e06c75</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Changed</string>
<key>scope</key>
<string>markup.changed</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#c678dd</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Colors</string>
<key>scope</key>
<string>constant.other.color</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#56b6c2</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Regular Expressions</string>
<key>scope</key>
<string>string.regexp</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#56b6c2</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Escape Characters</string>
<key>scope</key>
<string>constant.character.escape</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#56b6c2</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Embedded</string>
<key>scope</key>
<string>punctuation.section.embedded, variable.interpolation</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#c678dd</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Illegal</string>
<key>scope</key>
<string>invalid.illegal</string>
<key>settings</key>
<dict>
<key>background</key>
<string>#e06c75</string>
<key>foreground</key>
<string>#c8ccd4</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Broken</string>
<key>scope</key>
<string>invalid.broken</string>
<key>settings</key>
<dict>
<key>background</key>
<string>#d19a66</string>
<key>foreground</key>
<string>#282c34</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Deprecated</string>
<key>scope</key>
<string>invalid.deprecated</string>
<key>settings</key>
<dict>
<key>background</key>
<string>#be5046</string>
<key>foreground</key>
<string>#c8ccd4</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Unimplemented</string>
<key>scope</key>
<string>invalid.unimplemented</string>
<key>settings</key>
<dict>
<key>background</key>
<string>#545862</string>
<key>foreground</key>
<string>#c8ccd4</string>
</dict>
</dict>
</array>
<key>uuid</key>
<string>uuid</string>
</dict>
</plist>

View File

@ -1,4 +1,4 @@
**codesnap.nvim** 📸 Snapshot plugin that can make pretty code snapshots with real-time previews for Neovim
Author: Mist <mist.zzh@gmail.com>
version: 1.6.0
version: 0.0.9

1975
generator/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,19 +0,0 @@
[package]
name = "generator"
version = "0.1.0"
edition = "2021"
[dependencies]
nvim-oxi = { features = ["neovim-0-9", "libuv", "oxi-libuv"], version = "0.3" }
tiny-skia = "0.11.4"
syntect = "5.2.0"
cosmic-text = "0.12.0"
serde = "1.0.204"
arboard = { features = ["wayland-data-control"], version = "3.4.0" }
thiserror = "1.0.63"
regex = "1.10.5"
two-face = "0.4.0"
cached = "0.53.1"
[lib]
crate-type = ["cdylib"]

View File

@ -1,84 +0,0 @@
use cached::proc_macro::cached;
use regex::Regex;
const MIN_WIDTH: f32 = 100.;
pub const CHAR_WIDTH: f32 = 9.05;
fn min_width(width: f32) -> f32 {
if width < MIN_WIDTH {
MIN_WIDTH
} else {
width
}
}
pub fn calc_max_line_number_length(code_length: usize, start_line_number: usize) -> usize {
let max_line_number = code_length + start_line_number;
// If code length is 1, the max_line_number will equal to start_line_number
(max_line_number - 1).to_string().len()
}
pub fn calc_wh(text: &str, char_wdith: f32, line_height: f32) -> (f32, f32) {
let trimmed_text = prepare_code(text);
let lines = trimmed_text.lines();
let max_length_line = lines.clone().into_iter().fold("", |max_length_line, cur| {
if cur.len() > max_length_line.len() {
cur
} else {
max_length_line
}
});
let width = max_length_line.len() as f32 * char_wdith;
let height = lines.collect::<Vec<&str>>().len() as f32 * line_height;
(width, height)
}
// Because the code block is input by users, we need to calculate the width and height
// to make sure render the width and height of the "editor" shape correctly
#[cached(key = "String", convert = r#"{ format!("{}", text) }"#)]
pub fn calc_wh_with_min_width(text: &str, char_wdith: f32, line_height: f32) -> (f32, f32) {
let (width, height) = calc_wh(text, char_wdith, line_height);
(min_width(width), height)
}
// The tab character is incorrectly render using cosmic, need to replace all tab with space
// before render the code
fn replace_tab_to_space(text: &str) -> String {
let spaces = " ".repeat(2);
str::replace(text, "\t", &spaces)
}
// Find min indention of code lines, and remove the same indention from subsequent lines
fn trim_space(text: &str) -> String {
let lines = text.split("\n").collect::<Vec<&str>>();
let regex = Regex::new(r"(?:^|\n)(\s*)").unwrap();
let captures_iter = regex.captures_iter(text);
let space_lengths = captures_iter
.map(|capture| capture.get(1).unwrap().as_str().len())
.collect::<Vec<usize>>();
if space_lengths.len() < lines.len() {
return text.to_string();
}
let need_to_remove_spaces = " ".repeat(space_lengths.into_iter().min().unwrap());
lines
.into_iter()
.map(|line| {
Regex::new(format!("^{}", need_to_remove_spaces).as_ref())
.unwrap()
.replace(line, "")
.to_string()
})
.collect::<Vec<String>>()
.join("\n")
}
pub fn prepare_code(code: &str) -> String {
trim_space(&replace_tab_to_space(&code))
}

View File

@ -1,44 +0,0 @@
use std::i64;
use tiny_skia::Color;
const HEX_COLOR_LENGTH: usize = 7;
const HEX_COLOR_WITH_ALPHA_LENGTH: usize = 9;
pub struct RgbaColor {
pub color: Color,
}
pub fn is_valid_hex_color(color: &str) -> bool {
(color.len() == HEX_COLOR_LENGTH || color.len() == HEX_COLOR_WITH_ALPHA_LENGTH)
&& color.starts_with("#")
}
fn parse_color_to_rgba_hex(hex: &str) -> String {
if !is_valid_hex_color(&hex) || hex.len() == HEX_COLOR_WITH_ALPHA_LENGTH {
hex.to_string()
} else {
format!("{}ff", hex)
}
}
impl Into<RgbaColor> for String {
fn into(self) -> RgbaColor {
let rgba_hex_color = parse_color_to_rgba_hex(&self);
// Remove the '#' symbol
let hex_color = &rgba_hex_color.to_lowercase()[1..rgba_hex_color.len()];
let chars = hex_color.chars().collect::<Vec<char>>();
let splits = &chars
.chunks(2)
.map(|chunk| i64::from_str_radix(&chunk.iter().collect::<String>(), 16).unwrap())
.collect::<Vec<_>>();
RgbaColor {
color: Color::from_rgba8(
splits[0] as u8,
splits[1] as u8,
splits[2] as u8,
splits[3] as u8,
),
}
}
}

View File

@ -1,10 +0,0 @@
pub mod background;
pub mod breadcrumbs;
pub mod code_block;
pub mod container;
pub mod editor;
pub mod highlight_code_block;
pub mod interface;
pub mod line_number;
pub mod rect;
pub mod watermark;

View File

@ -1,147 +0,0 @@
use tiny_skia::{
Color, GradientStop, LinearGradient, Paint, Pixmap, Point, Rect, SpreadMode, Transform,
};
use crate::{
color::{is_valid_hex_color, RgbaColor},
edges::{edge::Edge, padding::Padding},
};
use super::interface::{
component::{Component, ComponentContext, RenderParams},
render_error::{self, RenderError},
style::{ComponentAlign, ComponentStyle, RawComponentStyle},
};
pub struct Background {
children: Vec<Box<dyn Component>>,
padding: Padding,
}
impl Background {
pub fn new(padding: Padding, children: Vec<Box<dyn Component>>) -> Background {
Background { children, padding }
}
pub fn parse_background_padding(
horizontal_background_padding: f32,
vertical_background_padding: f32,
background_padding: Option<f32>,
) -> Padding {
match background_padding {
Some(padding) => Padding::from_value(padding),
None => Padding {
top: vertical_background_padding,
bottom: vertical_background_padding,
left: horizontal_background_padding,
right: horizontal_background_padding,
},
}
}
pub fn has_background(padding: &Padding) -> bool {
return padding.horizontal() != 0. || padding.vertical() != 0.;
}
}
impl Component for Background {
fn children(&self) -> &Vec<Box<dyn Component>> {
&self.children
}
fn style(&self) -> RawComponentStyle {
RawComponentStyle::default()
.align(ComponentAlign::Column)
.padding(self.padding.clone())
}
fn self_render_condition(&self) -> bool {
Self::has_background(&self.padding)
}
fn draw_self(
&self,
pixmap: &mut Pixmap,
context: &ComponentContext,
_render_params: &RenderParams,
_style: &ComponentStyle,
_parent_style: &ComponentStyle,
) -> render_error::Result<()> {
let mut paint = Paint::default();
let w = pixmap.width() as f32;
let h = pixmap.height() as f32;
let params = &context.take_snapshot_params;
paint.anti_alias = false;
match params.bg_color.as_ref() {
Some(color) => {
if !is_valid_hex_color(color) {
return Err(RenderError::InvalidHexColor(color.to_string()));
}
let rgba_color: RgbaColor = color.to_string().into();
paint.set_color(rgba_color.color);
}
None => {
paint.shader = LinearGradient::new(
Point::from_xy(0., 0.),
Point::from_xy(w, 0.),
Background::get_theme(&context.take_snapshot_params.bg_theme)?,
SpreadMode::Pad,
Transform::identity(),
)
.unwrap();
}
};
pixmap.fill_rect(
Rect::from_xywh(0., 0., w, h).unwrap(),
&paint,
Transform::identity(),
None,
);
Ok(())
}
}
impl Background {
fn get_theme(theme: &str) -> render_error::Result<Vec<GradientStop>> {
let theme = match theme {
"default" => vec![
GradientStop::new(0.0, Color::from_rgba8(58, 28, 113, 255)),
GradientStop::new(0.5, Color::from_rgba8(215, 109, 119, 255)),
GradientStop::new(0.95, Color::from_rgba8(255, 175, 123, 255)),
],
"sea" => vec![
GradientStop::new(0.0, Color::from_rgba8(31, 162, 255, 255)),
GradientStop::new(0.4, Color::from_rgba8(18, 216, 250, 255)),
GradientStop::new(0.95, Color::from_rgba8(166, 255, 203, 255)),
],
"grape" => vec![
GradientStop::new(0.28, Color::from_rgba8(103, 90, 247, 255)),
GradientStop::new(0.95, Color::from_rgba8(189, 101, 250, 255)),
],
"peach" => vec![
GradientStop::new(0.22, Color::from_rgba8(221, 94, 137, 255)),
GradientStop::new(0.95, Color::from_rgba8(247, 187, 151, 255)),
],
"summer" => vec![
GradientStop::new(0.28, Color::from_rgba8(248, 165, 194, 255)),
GradientStop::new(0.95, Color::from_rgba8(116, 185, 255, 255)),
],
"bamboo" => vec![
GradientStop::new(0.22, Color::from_rgba8(107, 203, 165, 255)),
GradientStop::new(0.95, Color::from_rgba8(202, 244, 194, 255)),
],
"dusk" => vec![
GradientStop::new(0.22, Color::from_rgba8(255, 98, 110, 255)),
GradientStop::new(0.95, Color::from_rgba8(255, 190, 113, 255)),
],
_ => return Err(RenderError::UnknownBackgroundTheme(theme.to_string())),
};
Ok(theme)
}
}

View File

@ -1,90 +0,0 @@
use cosmic_text::{Attrs, Color, Family};
use regex::Regex;
use crate::{code::calc_wh_with_min_width, edges::margin::Margin, text::FontRenderer};
use super::interface::{
component::Component,
style::{ComponentStyle, RawComponentStyle, Size},
};
pub struct Breadcrumbs {
children: Vec<Box<dyn Component>>,
path: String,
line_height: f32,
has_breadcrumbs: bool,
}
impl Component for Breadcrumbs {
fn children(&self) -> &Vec<Box<dyn Component>> {
&self.children
}
fn style(&self) -> RawComponentStyle {
let style = RawComponentStyle::default();
if self.has_breadcrumbs {
let (w, h) = calc_wh_with_min_width(&self.path, 8., self.line_height);
style.size(Size::Num(w), Size::Num(h)).margin(Margin {
top: 5.,
..Margin::default()
})
} else {
style
}
}
fn draw_self(
&self,
pixmap: &mut tiny_skia::Pixmap,
context: &super::interface::component::ComponentContext,
render_params: &super::interface::component::RenderParams,
style: &super::interface::style::ComponentStyle,
_parent_style: &ComponentStyle,
) -> super::interface::render_error::Result<()> {
if self.has_breadcrumbs {
let attrs = Attrs::new()
.color(Color::rgb(128, 132, 139))
.family(Family::Name(&context.take_snapshot_params.code_font_family));
FontRenderer::new(
12.,
self.line_height,
context.scale_factor,
&context.take_snapshot_params.fonts_folder,
)
.draw_text(
render_params.x,
render_params.y,
style.width,
self.line_height,
vec![(&self.path, attrs)],
pixmap,
);
}
Ok(())
}
}
impl Breadcrumbs {
pub fn from_path(
path: String,
line_height: f32,
separator: String,
has_breadcrumbs: bool,
) -> Breadcrumbs {
let path = Regex::new("/")
.unwrap()
.replace_all(&path, separator)
.to_string();
Breadcrumbs {
children: vec![],
path,
line_height,
has_breadcrumbs,
}
}
}

View File

@ -1,17 +0,0 @@
use super::interface::component::Component;
pub struct CodeBlock {
children: Vec<Box<dyn Component>>,
}
impl Component for CodeBlock {
fn children(&self) -> &Vec<Box<dyn Component>> {
&self.children
}
}
impl CodeBlock {
pub fn from_children(children: Vec<Box<dyn Component>>) -> CodeBlock {
CodeBlock { children }
}
}

View File

@ -1,42 +0,0 @@
use tiny_skia::Pixmap;
use super::interface::{
component::{Component, ComponentContext, ComponentRenderParams},
render_error::Result,
style::Style,
};
pub struct Container {
children: Vec<Box<dyn Component>>,
}
impl Component for Container {
fn children(&self) -> &Vec<Box<dyn Component>> {
&self.children
}
}
impl Container {
pub fn from_children(children: Vec<Box<dyn Component>>) -> Container {
Container { children }
}
pub fn draw_root(&self, context: &ComponentContext) -> Result<Pixmap> {
let style = self.parsed_style();
let mut pixmap = Pixmap::new(
(style.width * context.scale_factor) as u32,
(style.height * context.scale_factor) as u32,
)
.unwrap();
self.draw(
&mut pixmap,
context,
ComponentRenderParams::default(),
Style::default(),
Style::default(),
)?;
Ok(pixmap)
}
}

View File

@ -1,2 +0,0 @@
pub mod code;
pub mod mac_title_bar;

View File

@ -1,75 +0,0 @@
use crate::{
code::{calc_wh_with_min_width, prepare_code, CHAR_WIDTH},
components::interface::{
component::{Component, ComponentContext, RenderParams},
render_error,
style::{ComponentStyle, RawComponentStyle, Size, Style},
},
highlight::Highlight,
text::FontRenderer,
};
pub struct Code {
children: Vec<Box<dyn Component>>,
line_height: f32,
font_size: f32,
value: String,
}
impl Component for Code {
fn children(&self) -> &Vec<Box<dyn Component>> {
&self.children
}
fn style(&self) -> RawComponentStyle {
let (w, h) = calc_wh_with_min_width(&self.value, CHAR_WIDTH, self.line_height);
Style::default().size(Size::Num(w), Size::Num(h))
}
fn draw_self(
&self,
pixmap: &mut tiny_skia::Pixmap,
context: &ComponentContext,
render_params: &RenderParams,
style: &ComponentStyle,
_parent_style: &ComponentStyle,
) -> render_error::Result<()> {
let params = &context.take_snapshot_params;
let highlight = Highlight::new(
self.value.clone(),
params.code_font_family.clone(),
params.code_file_path.clone(),
params.extension.clone(),
);
let highlight_result = highlight.parse(&params.themes_folder, &params.theme)?;
FontRenderer::new(
self.font_size,
self.line_height,
context.scale_factor,
&context.take_snapshot_params.fonts_folder,
)
.draw_text(
render_params.x,
render_params.y,
style.width,
style.height,
highlight_result.clone(),
pixmap,
);
Ok(())
}
}
impl Code {
pub fn new(value: String, line_height: f32, font_size: f32) -> Code {
Code {
value: prepare_code(&value),
line_height,
font_size,
children: vec![],
}
}
}

View File

@ -1,109 +0,0 @@
use tiny_skia::{Color, FillRule, Paint, PathBuilder, Transform};
use crate::{
components::interface::{
component::{Component, ComponentContext, RenderParams},
render_error,
style::{ComponentStyle, RawComponentStyle, Size, Style},
},
edges::margin::Margin,
};
pub struct MacTitleBar {
radius: f32,
children: Vec<Box<dyn Component>>,
render_condition: bool,
}
impl Component for MacTitleBar {
fn children(&self) -> &Vec<Box<dyn Component>> {
&self.children
}
fn style(&self) -> RawComponentStyle {
let demeter = self.radius * 2.;
Style::default()
.size(Size::Num(demeter + 2. * 25.), Size::Num(demeter))
.margin(Margin {
bottom: 10.,
..Margin::default()
})
}
fn render_condition(&self) -> bool {
return self.render_condition;
}
fn draw_self(
&self,
pixmap: &mut tiny_skia::Pixmap,
context: &ComponentContext,
render_params: &RenderParams,
_style: &ComponentStyle,
_parent_style: &ComponentStyle,
) -> render_error::Result<()> {
self.draw_control_buttons(
// Control bar construct by draw circles, after drawn, the path will be at the center,
// so the x, y need to offset by radius of the circle, and the next shape will still
// be drwan on the original point
render_params.x + self.radius,
render_params.y + self.radius,
pixmap,
vec![
Color::from_rgba8(255, 94, 87, 255),
Color::from_rgba8(255, 186, 46, 255),
Color::from_rgba8(43, 200, 65, 255),
],
25.,
Transform::from_scale(context.scale_factor, context.scale_factor),
);
Ok(())
}
}
impl MacTitleBar {
pub fn from_radius(radius: f32, render_condition: bool) -> MacTitleBar {
MacTitleBar {
radius,
children: vec![],
render_condition,
}
}
fn draw_control_buttons(
&self,
x: f32,
y: f32,
pixmap: &mut tiny_skia::Pixmap,
colors: Vec<Color>,
gap: f32,
transform: Transform,
) {
for (index, color) in colors.into_iter().enumerate() {
self.draw_control_button(x, y, pixmap, color, index as f32 * gap, transform);
}
}
fn draw_control_button(
&self,
x: f32,
y: f32,
pixmap: &mut tiny_skia::Pixmap,
color: Color,
x_offset: f32,
transform: Transform,
) {
let mut path_builder = PathBuilder::new();
path_builder.push_circle(x + x_offset, y, self.radius);
path_builder.close();
let path = path_builder.finish().unwrap();
let mut paint = Paint::default();
paint.set_color(color);
pixmap.fill_path(&path, &paint, FillRule::Winding, transform, None);
}
}

View File

@ -1,76 +0,0 @@
use super::{
interface::{component::Component, style::ComponentStyle},
rect::EDITOR_PADDING,
};
use tiny_skia::{Color, Paint, Rect, Transform};
#[derive(Default)]
pub struct HighlightCodeBlock {
children: Vec<Box<dyn Component>>,
line_height: f32,
start_line_number: usize,
end_line_number: usize,
render_condition: bool,
}
impl Component for HighlightCodeBlock {
fn children(&self) -> &Vec<Box<dyn Component>> {
&self.children
}
fn render_condition(&self) -> bool {
self.render_condition
}
fn draw_self(
&self,
pixmap: &mut tiny_skia::Pixmap,
context: &super::interface::component::ComponentContext,
render_params: &super::interface::component::RenderParams,
_style: &super::interface::style::ComponentStyle,
parent_style: &ComponentStyle,
) -> super::interface::render_error::Result<()> {
let mut paint = Paint::default();
let start_y_offset = (self.start_line_number - 1) as f32 * self.line_height;
paint.anti_alias = false;
paint.set_color(Color::from_rgba8(255, 255, 255, 10));
pixmap.fill_rect(
Rect::from_xywh(
render_params.x - EDITOR_PADDING,
render_params.y + start_y_offset,
parent_style.width + EDITOR_PADDING * 2.,
(self.end_line_number - self.start_line_number + 1) as f32 * self.line_height,
)
.unwrap(),
&paint,
Transform::from_scale(context.scale_factor, context.scale_factor),
None,
);
Ok(())
}
}
impl HighlightCodeBlock {
pub fn from_line_number(
start_line_number: Option<usize>,
end_line_number: Option<usize>,
line_height: f32,
) -> HighlightCodeBlock {
if end_line_number < start_line_number {
panic!("end_line_number should be greater than start_line_number")
}
match start_line_number {
Some(start_line_number) => HighlightCodeBlock {
render_condition: true,
children: vec![],
line_height,
start_line_number,
end_line_number: end_line_number.unwrap(),
},
None => HighlightCodeBlock::default(),
}
}
}

View File

@ -1,3 +0,0 @@
pub mod component;
pub mod render_error;
pub mod style;

View File

@ -1,204 +0,0 @@
use super::{
render_error,
style::{ComponentAlign, ComponentStyle, RawComponentStyle, Size, Style},
};
use crate::{config::TakeSnapshotParams, edges::edge::Edge};
use std::sync::Arc;
use tiny_skia::Pixmap;
pub struct ComponentContext {
pub scale_factor: f32,
pub take_snapshot_params: Arc<TakeSnapshotParams>,
}
#[derive(Default, Clone)]
pub struct RenderParams {
pub x: f32,
pub y: f32,
}
#[derive(Default)]
pub struct ComponentRenderParams {
pub parent_render_params: RenderParams,
pub sibling_render_params: RenderParams,
}
impl ComponentRenderParams {
fn parse_into_render_params_with_style(
&self,
parent_style: ComponentStyle,
sibling_style: ComponentStyle,
style: ComponentStyle,
) -> RenderParams {
match parent_style.align {
ComponentAlign::Row => RenderParams {
x: self.sibling_render_params.x
+ sibling_style.width
+ style.margin.left
+ sibling_style.padding.horizontal(),
y: self.sibling_render_params.y + style.margin.top,
},
ComponentAlign::Column => RenderParams {
x: self.sibling_render_params.x + style.margin.left,
y: self.sibling_render_params.y
+ style.margin.top
+ sibling_style.height
+ sibling_style.padding.vertical(),
},
}
}
}
pub trait Component {
fn children(&self) -> &Vec<Box<dyn Component>>;
fn align(&self) -> ComponentAlign {
ComponentAlign::Row
}
fn initialize(&self, render_params: &RenderParams) -> RenderParams {
render_params.clone()
}
// The render_condition determines whether the component should be rendered or not
fn render_condition(&self) -> bool {
true
}
// The difference with render_condition is that self_render_condition still renders childrens
fn self_render_condition(&self) -> bool {
true
}
fn draw_self(
&self,
_pixmap: &mut Pixmap,
_context: &ComponentContext,
_render_params: &RenderParams,
_style: &ComponentStyle,
_parent_style: &ComponentStyle,
) -> render_error::Result<()> {
Ok(())
}
fn style(&self) -> RawComponentStyle {
RawComponentStyle::default()
}
fn parse_size(&self, size: Size, dynamic_value: f32) -> f32 {
match size {
Size::Num(num) => num,
Size::Dynamic => dynamic_value,
}
}
fn parsed_style(&self) -> Style<f32> {
// If render_condition return false, the whole component shouldn't rendered,
// includes its children
if !self.render_condition() {
return ComponentStyle::default();
}
// If self_render_condition return false, the component shouldn't rendered,
// so the corresponding style should be cleared
let style = if self.self_render_condition() {
self.style()
} else {
RawComponentStyle::default()
};
let (width, height) = self.get_dynamic_wh();
let width = self.parse_size(style.width, width)
+ style.padding.horizontal()
+ style.margin.horizontal();
Style {
min_width: style.min_width,
width: if width > style.min_width {
width
} else {
style.min_width
},
height: self.parse_size(style.height, height)
+ style.padding.vertical()
+ style.margin.vertical(),
align: style.align,
padding: style.padding,
margin: style.margin,
}
}
fn draw(
&self,
pixmap: &mut Pixmap,
context: &ComponentContext,
component_render_params: ComponentRenderParams,
parent_style: ComponentStyle,
sibling_style: ComponentStyle,
) -> render_error::Result<RenderParams> {
let style = self.parsed_style();
let render_params = self.initialize(
&component_render_params.parse_into_render_params_with_style(
parent_style.clone(),
sibling_style.clone(),
style.clone(),
),
);
// Render nothing on paint if render_condition return false
if !self.render_condition() {
return Ok(render_params.clone());
}
if self.self_render_condition() {
self.draw_self(pixmap, context, &render_params, &style, &parent_style)?;
}
let children = self.children();
let mut sibling_render_params = RenderParams {
x: render_params.x + style.padding.left,
y: render_params.y + style.padding.top,
};
let mut sibling_style = ComponentStyle::default();
for child in children {
sibling_render_params = child.draw(
pixmap,
context,
ComponentRenderParams {
parent_render_params: render_params.clone(),
sibling_render_params,
},
style.clone(),
sibling_style,
)?;
sibling_style = child.parsed_style();
}
Ok(render_params.clone())
}
// Dynamic calculate width and height of children, if the children is empty, get_dynamic_wh
// will return (0., 0.)
fn get_dynamic_wh(&self) -> (f32, f32) {
let children = self.children();
let calc_children_wh = |cb: fn((f32, f32), &Box<dyn Component>) -> (f32, f32)| {
children.iter().fold((0., 0.), cb)
};
let style = self.style();
match style.align {
// If align is row, width is sum of children width, height is max of children height
ComponentAlign::Row => calc_children_wh(|(w, h), child| {
let style = child.parsed_style();
(w + style.width, h.max(style.height))
}),
// If align is column, width is max of children width, height is sum of children height
ComponentAlign::Column => calc_children_wh(|(w, h), child| {
let style = child.parsed_style();
(w.max(style.width), h + style.height)
}),
}
}
}

View File

@ -1,28 +0,0 @@
use nvim_oxi::lua;
use thiserror::Error;
pub type Result<T> = std::result::Result<T, RenderError>;
#[derive(Debug, Error)]
pub enum RenderError {
#[error("Highlight code failed!")]
HighlightThemeLoadFailed,
#[error("No such highlight syntax for {0}")]
HighlightCodeFailed(String),
#[error("Unable to parse unknown background theme {0}")]
UnknownBackgroundTheme(String),
#[error("Invalid hex color {0}")]
InvalidHexColor(String),
#[error("No such file {0}")]
NoSuchFile(String),
}
impl From<RenderError> for nvim_oxi::Error {
fn from(err: RenderError) -> Self {
nvim_oxi::Error::Lua(lua::Error::RuntimeError(err.to_string()))
}
}

View File

@ -1,80 +0,0 @@
use crate::edges::{margin::Margin, padding::Padding};
#[derive(Clone, Debug)]
pub enum ComponentAlign {
Row,
Column,
}
pub enum Size {
Dynamic,
Num(f32),
}
#[derive(Clone, Debug)]
pub struct Style<T> {
pub width: T,
pub height: T,
pub min_width: f32,
pub align: ComponentAlign,
pub padding: Padding,
pub margin: Margin,
}
pub type RawComponentStyle = Style<Size>;
pub type ComponentStyle = Style<f32>;
impl Default for RawComponentStyle {
fn default() -> Self {
Style {
min_width: 0.,
width: Size::Dynamic,
height: Size::Dynamic,
align: ComponentAlign::Row,
padding: Padding::default(),
margin: Margin::default(),
}
}
}
impl Default for ComponentStyle {
fn default() -> Self {
Style {
min_width: 0.,
width: 0.,
height: 0.,
align: ComponentAlign::Row,
padding: Padding::default(),
margin: Margin::default(),
}
}
}
impl RawComponentStyle {
pub fn size(mut self, width: Size, height: Size) -> Self {
self.width = width;
self.height = height;
self
}
// Only works if the width is calculate dynamically
pub fn min_width(mut self, min_width: f32) -> Self {
self.min_width = min_width;
self
}
pub fn align(mut self, align: ComponentAlign) -> Self {
self.align = align;
self
}
pub fn padding(mut self, padding: Padding) -> Self {
self.padding = padding;
self
}
pub fn margin(mut self, margin: Margin) -> Self {
self.margin = margin;
self
}
}

View File

@ -1,100 +0,0 @@
use super::interface::{
component::{Component, ComponentContext, RenderParams},
render_error,
style::{ComponentStyle, RawComponentStyle, Size, Style},
};
use crate::{code::CHAR_WIDTH, edges::margin::Margin, text::FontRenderer};
use cosmic_text::{Attrs, Color, Family};
const FONT_SIZE: f32 = 14.;
#[derive(Default)]
pub struct LineNumber {
children: Vec<Box<dyn Component>>,
line_height: f32,
render_condition: bool,
line_number_content: Vec<String>,
number_of_digit: usize,
}
impl Component for LineNumber {
fn render_condition(&self) -> bool {
return self.render_condition;
}
fn children(&self) -> &Vec<Box<dyn Component>> {
&self.children
}
fn style(&self) -> RawComponentStyle {
Style::default()
.size(
Size::Num(CHAR_WIDTH * self.number_of_digit as f32),
Size::Num(self.line_number_content.len() as f32 * self.line_height),
)
.margin(Margin {
right: 10.,
..Margin::default()
})
}
fn draw_self(
&self,
pixmap: &mut tiny_skia::Pixmap,
context: &ComponentContext,
render_params: &RenderParams,
style: &ComponentStyle,
_parent_style: &ComponentStyle,
) -> render_error::Result<()> {
FontRenderer::new(
FONT_SIZE,
self.line_height,
context.scale_factor,
&context.take_snapshot_params.fonts_folder,
)
.draw_text(
render_params.x,
render_params.y,
style.width,
style.height,
vec![(
&self.line_number_content.join("\n"),
Attrs::new()
.color(Color::rgb(73, 81, 98))
.family(Family::Name(&context.take_snapshot_params.code_font_family)),
)],
pixmap,
);
Ok(())
}
}
impl LineNumber {
pub fn new(content: &str, start_line_number: Option<usize>, line_height: f32) -> LineNumber {
match start_line_number {
None => LineNumber::default(),
Some(start_line_number) => {
let lines = content.split("\n").collect::<Vec<&str>>();
let max_line_number = lines.len() + start_line_number;
let number_of_digit = (max_line_number - 1).to_string().len();
LineNumber {
line_number_content: (start_line_number..max_line_number)
.map(|line_number| {
format!(
"{:>width$}",
line_number.to_string(),
width = number_of_digit
)
})
.collect::<Vec<String>>(),
number_of_digit,
children: vec![],
render_condition: true,
line_height,
}
}
}
}
}

View File

@ -1,106 +0,0 @@
use super::interface::{
component::{Component, ComponentContext, RenderParams},
render_error,
style::{ComponentAlign, ComponentStyle, RawComponentStyle, Style},
};
use crate::edges::padding::Padding;
use tiny_skia::{FillRule, Paint, PathBuilder, Pixmap, Transform};
pub const EDITOR_PADDING: f32 = 20.;
pub struct Rect {
radius: f32,
min_width: f32,
children: Vec<Box<dyn Component>>,
}
impl Component for Rect {
fn children(&self) -> &Vec<Box<dyn Component>> {
&self.children
}
fn style(&self) -> RawComponentStyle {
Style::default()
.min_width(self.min_width)
.align(ComponentAlign::Column)
.padding(Padding::from_value(EDITOR_PADDING))
}
fn draw_self(
&self,
pixmap: &mut Pixmap,
context: &ComponentContext,
render_params: &RenderParams,
style: &ComponentStyle,
_parent_style: &ComponentStyle,
) -> render_error::Result<()> {
let mut path_builder = PathBuilder::new();
let x = render_params.x;
let y = render_params.y;
let w = style.width;
let h = style.height;
let rect_width = w - 2. * self.radius;
let rect_height = h - 2. * self.radius;
path_builder.move_to(x + self.radius, y);
path_builder.line_to(x + self.radius + rect_width, y);
path_builder.line_to(x + self.radius + rect_width, y + self.radius);
path_builder.line_to(x + rect_width + self.radius * 2., y + self.radius);
path_builder.line_to(
x + rect_width + self.radius * 2.,
y + rect_height + self.radius,
);
path_builder.line_to(x + rect_width + self.radius, y + rect_height + self.radius);
path_builder.line_to(
x + rect_width + self.radius,
y + rect_height + self.radius * 2.,
);
path_builder.line_to(x + self.radius, y + rect_height + self.radius * 2.);
path_builder.line_to(x + self.radius, y + rect_height + self.radius);
path_builder.line_to(x, y + rect_height + self.radius);
path_builder.line_to(x, y + self.radius);
path_builder.line_to(x + self.radius, y + self.radius);
path_builder.line_to(x + self.radius, y);
path_builder.line_to(x + self.radius + rect_width, y);
path_builder.push_circle(
x + rect_width + self.radius,
y + rect_height + self.radius,
self.radius,
);
path_builder.push_circle(x + self.radius + rect_width, y + self.radius, self.radius);
path_builder.push_circle(x + self.radius, y + self.radius, self.radius);
path_builder.push_circle(x + self.radius, y + rect_height + self.radius, self.radius);
path_builder.close();
let path = path_builder.finish().unwrap();
let mut paint = Paint::default();
paint.set_color_rgba8(40, 44, 52, 237);
pixmap.fill_path(
&path,
&paint,
FillRule::Winding,
Transform::from_scale(context.scale_factor, context.scale_factor),
// Transform::identity(),
None,
);
Ok(())
}
}
impl Rect {
pub fn new(radius: f32, min_width: Option<f32>, children: Vec<Box<dyn Component>>) -> Rect {
Rect {
radius,
children,
min_width: min_width.unwrap_or(0.),
}
}
}

View File

@ -1,82 +0,0 @@
use cosmic_text::{Align, Attrs, Family};
use tiny_skia::Pixmap;
use crate::{edges::margin::Margin, text::FontRenderer};
use super::interface::{
component::{Component, ComponentContext, RenderParams},
render_error,
style::{ComponentStyle, RawComponentStyle},
};
pub struct Watermark {
children: Vec<Box<dyn Component>>,
value: String,
}
impl Component for Watermark {
fn draw_self(
&self,
pixmap: &mut Pixmap,
context: &ComponentContext,
render_params: &RenderParams,
_style: &ComponentStyle,
_parent_style: &ComponentStyle,
) -> render_error::Result<()> {
let params = &context.take_snapshot_params;
let attrs = Attrs::new().family(Family::Name(
&context.take_snapshot_params.watermark_font_family,
));
FontRenderer::new(
20.,
20.,
context.scale_factor,
&context.take_snapshot_params.fonts_folder,
)
.draw_line(
0.,
render_params.y,
pixmap.width() as f32,
pixmap.height() as f32,
&params.watermark,
attrs,
Some(Align::Center),
pixmap,
);
Ok(())
}
fn children(&self) -> &Vec<Box<dyn Component>> {
&self.children
}
fn render_condition(&self) -> bool {
self.value != ""
}
fn style(&self) -> RawComponentStyle {
let default_style = RawComponentStyle::default();
if self.value != "" {
default_style.margin(Margin {
bottom: 22.,
top: 15.,
..Margin::default()
})
} else {
default_style
}
}
}
impl Watermark {
pub fn new(value: String) -> Watermark {
Watermark {
children: vec![],
value,
}
}
}

View File

@ -1,63 +0,0 @@
use nvim_oxi::conversion::{Error as ConversionError, FromObject, ToObject};
use nvim_oxi::serde::{Deserializer, Serializer};
use nvim_oxi::{lua, Object};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone)]
pub struct TakeSnapshotParams {
// Whether to display the MacOS style title bar
pub mac_window_bar: bool,
// Wartermark of the code snapshot
pub watermark: String,
// Editor title
pub title: Option<String>,
pub code_font_family: String,
pub watermark_font_family: String,
pub code: String,
pub code_file_path: String,
pub extension: Option<String>,
pub save_path: Option<String>,
pub themes_folder: String,
pub fonts_folder: String,
pub theme: String,
pub bg_theme: String,
pub bg_color: Option<String>,
// Breadcrumbs path
pub file_path: String,
pub breadcrumbs_separator: String,
pub has_breadcrumbs: bool,
pub start_line_number: Option<usize>,
pub highlight_start_line_number: Option<usize>,
pub highlight_end_line_number: Option<usize>,
pub min_width: Option<f32>,
pub bg_x_padding: f32,
pub bg_y_padding: f32,
pub bg_padding: Option<f32>,
}
impl FromObject for TakeSnapshotParams {
fn from_object(obj: Object) -> Result<Self, ConversionError> {
Self::deserialize(Deserializer::new(obj)).map_err(Into::into)
}
}
impl ToObject for TakeSnapshotParams {
fn to_object(self) -> Result<Object, ConversionError> {
self.serialize(Serializer::new()).map_err(Into::into)
}
}
impl lua::Poppable for TakeSnapshotParams {
unsafe fn pop(lstate: *mut lua::ffi::lua_State) -> Result<Self, lua::Error> {
let obj = Object::pop(lstate)?;
Self::from_object(obj).map_err(lua::Error::pop_error_from_err::<Self, _>)
}
}
impl lua::Pushable for TakeSnapshotParams {
unsafe fn push(self, lstate: *mut lua::ffi::lua_State) -> Result<std::ffi::c_int, lua::Error> {
self.to_object()
.map_err(lua::Error::push_error_from_err::<Self, _>)?
.push(lstate)
}
}

View File

@ -1,46 +0,0 @@
use crate::{config::TakeSnapshotParams, snapshot::take_snapshot};
#[cfg(target_os = "linux")]
use arboard::SetExtLinux;
use arboard::{Clipboard, ImageData};
use nvim_oxi::Result;
// The function will be called as FFI on Lua side
#[allow(dead_code)]
pub fn copy_into_clipboard(config: TakeSnapshotParams) -> Result<()> {
let pixmap = take_snapshot(config.clone())?;
let premultplied_colors = pixmap.pixels();
let colors = premultplied_colors
.iter()
.map(|premultplied_color| {
vec![
premultplied_color.red(),
premultplied_color.green(),
premultplied_color.blue(),
premultplied_color.alpha(),
]
})
.flatten()
.collect::<Vec<u8>>();
let img_data = ImageData {
width: pixmap.width() as usize,
height: pixmap.height() as usize,
bytes: colors.into(),
};
#[cfg(target_os = "linux")]
std::thread::spawn(move || {
Clipboard::new()
.unwrap()
.set()
.wait()
.image(img_data)
.unwrap();
});
#[cfg(not(target_os = "linux"))]
Clipboard::new().unwrap().set_image(img_data).unwrap();
Ok(())
}

View File

@ -1,77 +0,0 @@
use crate::{
code::{calc_max_line_number_length, calc_wh, prepare_code},
config::TakeSnapshotParams,
};
use arboard::Clipboard;
#[cfg(target_os = "linux")]
use arboard::SetExtLinux;
use nvim_oxi::Result;
use std::cmp::max;
const SPACE_BOTH_SIDE: usize = 2;
fn optional(component: String, is_view: bool) -> String {
if is_view {
component
} else {
"".to_string()
}
}
#[allow(dead_code)]
pub fn copy_ascii(params: TakeSnapshotParams) -> Result<()> {
let code = prepare_code(&params.code);
let (width, height) = calc_wh(&code, 1., 1.);
let calc_line_number_width =
|start_line_number: usize| calc_max_line_number_length(height as usize, start_line_number);
let frame_width = max(width as usize, params.file_path.len()) + SPACE_BOTH_SIDE;
let frame_width = match params.start_line_number {
Some(start_line_number) => {
frame_width + SPACE_BOTH_SIDE + calc_line_number_width(start_line_number)
}
None => frame_width,
};
let line = format!("{}\n", "".repeat(frame_width));
let frame_width_with_content = frame_width - 1;
let top_frame = format!("{}\n", "".repeat(frame_width));
let bottom_frame = format!("{}", "".repeat(frame_width));
let code = code
.lines()
.enumerate()
.map(|(i, line)| {
format!(
"│ {:1$} │\n",
match params.start_line_number {
Some(start_line_number) => format!(
"{:1$} {line}",
start_line_number + i,
calc_line_number_width(start_line_number),
),
None => line.to_string(),
},
frame_width_with_content - 1
)
})
.collect::<String>();
let text_line = |text: &str| format!("{:1$}\n", text, frame_width_with_content);
let breadcrumbs = optional(
format!("{}{line}", text_line(&params.file_path)),
params.has_breadcrumbs,
);
let ascii_snapshot = format!("{top_frame}{breadcrumbs}{code}{bottom_frame}");
#[cfg(target_os = "linux")]
std::thread::spawn(move || {
Clipboard::new()
.unwrap()
.set()
.wait()
.text(ascii_snapshot)
.unwrap();
});
#[cfg(not(target_os = "linux"))]
Clipboard::new().unwrap().set_text(ascii_snapshot).unwrap();
Ok(())
}

View File

@ -1,3 +0,0 @@
pub mod edge;
pub mod margin;
pub mod padding;

View File

@ -1,5 +0,0 @@
pub trait Edge {
fn horizontal(&self) -> f32;
fn vertical(&self) -> f32;
}

View File

@ -1,31 +0,0 @@
use super::edge::Edge;
#[derive(Clone, Default, Debug)]
pub struct Margin {
pub left: f32,
pub right: f32,
pub top: f32,
pub bottom: f32,
}
impl Edge for Margin {
fn horizontal(&self) -> f32 {
self.left + self.right
}
fn vertical(&self) -> f32 {
self.bottom + self.top
}
}
impl Margin {
#[allow(dead_code)]
pub fn from_value(value: f32) -> Margin {
Margin {
left: value,
right: value,
top: value,
bottom: value,
}
}
}

View File

@ -1,30 +0,0 @@
use super::edge::Edge;
#[derive(Clone, Default, Debug)]
pub struct Padding {
pub left: f32,
pub right: f32,
pub top: f32,
pub bottom: f32,
}
impl Edge for Padding {
fn horizontal(&self) -> f32 {
self.left + self.right
}
fn vertical(&self) -> f32 {
self.bottom + self.top
}
}
impl Padding {
pub fn from_value(value: f32) -> Padding {
Padding {
left: value,
right: value,
top: value,
bottom: value,
}
}
}

View File

@ -1,107 +0,0 @@
use std::collections::HashMap;
use cosmic_text::{Attrs, Family, Style, Weight};
use syntect::{
easy::HighlightLines,
highlighting::{FontStyle, ThemeSet},
parsing::{SyntaxReference, SyntaxSet},
util::LinesWithEndings,
};
use crate::components::interface::render_error::RenderError;
type SourceMap = HashMap<&'static str, &'static str>;
pub struct Highlight {
content: String,
code_file_path: String,
extension: Option<String>,
font_family: String,
highlighting_language_source_map: SourceMap,
}
pub type HighlightResult<'a> = Vec<(&'a str, Attrs<'a>)>;
impl Highlight {
pub fn new(
content: String,
font_family: String,
code_file_path: String,
extension: Option<String>,
) -> Highlight {
Highlight {
content,
code_file_path,
extension,
font_family,
highlighting_language_source_map: HashMap::from([("PHP", "<?php")]),
}
}
fn guess_syntax(&self, syntax_set: &SyntaxSet) -> Result<SyntaxReference, RenderError> {
// The extension exist only when users specified explicitly
// By default, using filepath to detect what syntax should use
let syntax = match &self.extension {
Some(extension) => syntax_set
.find_syntax_by_extension(&extension)
.ok_or(RenderError::HighlightCodeFailed(extension.to_string()))?,
None => syntax_set
.find_syntax_for_file(&self.code_file_path)
.map_err(|_| RenderError::NoSuchFile(self.code_file_path.to_string()))?
.ok_or(RenderError::HighlightCodeFailed(
self.code_file_path.to_string(),
))?,
};
// The Syntect clearly distinguish between PHP and PHP Source
// Should use PHP as highlight language if the source content contains "<php" tag
// Should use PHP Source as highlight language if the source content not contains "<php" tag
if let Some(identifier) = self.highlighting_language_source_map.get(&syntax.name[..]) {
if !self.content.contains(identifier) {
return Ok(syntax_set
.find_syntax_by_name(&format!("{} Source", &syntax.name))
.unwrap_or(syntax)
.to_owned());
}
}
Ok(syntax.to_owned())
}
pub fn parse(
&self,
theme_folder: &str,
theme: &str,
) -> Result<Vec<(&str, Attrs)>, RenderError> {
let syntax_set = two_face::syntax::extra_newlines();
let theme_set = ThemeSet::load_from_folder(theme_folder)
.map_err(|_| RenderError::HighlightThemeLoadFailed)?;
let syntax = &self.guess_syntax(&syntax_set)?;
let mut highlight = HighlightLines::new(syntax, &theme_set.themes[theme]);
let attrs = Attrs::new().family(Family::Name(self.font_family.as_ref()));
// Highlight the content line by line using highlight_line function
Ok(LinesWithEndings::from(&self.content)
.map(|line| {
highlight
.highlight_line(line, &syntax_set)
.unwrap()
.into_iter()
.map(|(style, str)| {
let syntect::highlighting::Color { r, g, b, a: _ } = style.foreground;
let attrs = match style.font_style {
FontStyle::BOLD => attrs.weight(Weight::BOLD),
FontStyle::ITALIC => attrs.style(Style::Italic),
FontStyle::UNDERLINE => attrs.style(Style::Normal),
_ => attrs,
};
(str, attrs.color(cosmic_text::Color::rgb(r, g, b)))
})
.collect::<HighlightResult>()
})
.fold(vec![], |acc, cur| [acc, cur].concat())
.into_iter()
.collect::<HighlightResult>())
}
}

View File

@ -1,29 +0,0 @@
mod code;
mod color;
mod components;
mod config;
mod copy;
mod copy_ascii;
mod edges;
mod highlight;
mod path;
mod save;
mod snapshot;
mod text;
use copy::copy_into_clipboard;
use copy_ascii::copy_ascii;
use nvim_oxi::{Dictionary, Function, Result};
use save::save_snapshot;
#[nvim_oxi::module]
fn generator() -> Result<Dictionary> {
Ok(Dictionary::from_iter([
(
"copy_into_clipboard",
Function::from_fn(copy_into_clipboard),
),
("save_snapshot", Function::from_fn(save_snapshot)),
("copy_ascii", Function::from_fn(copy_ascii)),
]))
}

View File

@ -1,10 +0,0 @@
use regex::Regex;
use std::env::{var, VarError};
pub fn parse_save_path(path: String) -> Result<String, VarError> {
let home_path = var("HOME")?;
let regex = Regex::new(r"(~|$HOME)").unwrap();
let path = regex.replace_all(&path, home_path);
Ok(path.to_string())
}

View File

@ -1,27 +0,0 @@
use crate::{config::TakeSnapshotParams, path::parse_save_path, snapshot::take_snapshot};
use nvim_oxi::{lua::Error::RuntimeError, Error, Result};
// The function will be called as FFI on Lua side
#[allow(dead_code)]
pub fn save_snapshot(config: TakeSnapshotParams) -> Result<()> {
match &config.save_path {
Some(path) => {
if !path.ends_with(".png") {
return Err(Error::Lua(RuntimeError(
"The save_path must ends with .png".to_string(),
)));
}
let pixmap = take_snapshot(config.clone())?;
let path = parse_save_path(path.to_string())
.map_err(|err| Error::Lua(RuntimeError(err.to_string())))?;
pixmap
.save_png(path)
.map_err(|err| Error::Lua(RuntimeError(err.to_string())))
}
None => Err(Error::Lua(RuntimeError(
"Cannot find 'save_path' in config".to_string(),
))),
}
}

View File

@ -1,78 +0,0 @@
use std::sync::Arc;
use tiny_skia::Pixmap;
use crate::components::background::Background;
use crate::components::breadcrumbs::Breadcrumbs;
use crate::components::code_block::CodeBlock;
use crate::components::container::Container;
use crate::components::editor::code::Code;
use crate::components::editor::mac_title_bar::MacTitleBar;
use crate::components::highlight_code_block::HighlightCodeBlock;
use crate::components::interface::component::ComponentContext;
use crate::components::interface::render_error;
use crate::components::line_number::LineNumber;
use crate::components::rect::Rect;
use crate::components::watermark::Watermark;
use crate::config::TakeSnapshotParams;
// Scale the screenshot to 3 times its size
const SCALE_FACTOR: f32 = 3.;
const LINE_HEIGHT: f32 = 20.;
const VIEW_WATERMARK_PADDING: f32 = 82.;
// The params is come from neovim instance
pub fn take_snapshot(params: TakeSnapshotParams) -> render_error::Result<Pixmap> {
let context = ComponentContext {
scale_factor: SCALE_FACTOR,
take_snapshot_params: Arc::new(params.clone()),
};
let background_padding = Background::parse_background_padding(
params.bg_x_padding,
params.bg_y_padding,
params.bg_padding,
);
// If vertical background padding is less than 82., should hidden watermark component
// If watermark text is equal to "", the watermark component is hidden
let watermark = if background_padding.bottom >= VIEW_WATERMARK_PADDING {
params.watermark
} else {
"".to_string()
};
let pixmap = Container::from_children(vec![Box::new(Background::new(
background_padding,
vec![
Box::new(Rect::new(
16.,
params.min_width,
vec![
Box::new(MacTitleBar::from_radius(8., params.mac_window_bar)),
Box::new(Breadcrumbs::from_path(
params.file_path,
15.,
params.breadcrumbs_separator,
params.has_breadcrumbs,
)),
Box::new(CodeBlock::from_children(vec![
Box::new(HighlightCodeBlock::from_line_number(
params.highlight_start_line_number,
params.highlight_end_line_number,
LINE_HEIGHT,
)),
Box::new(LineNumber::new(
&params.code,
params.start_line_number,
LINE_HEIGHT,
)),
Box::new(Code::new(params.code, LINE_HEIGHT, 15.)),
])),
],
)),
Box::new(Watermark::new(watermark)),
],
))])
.draw_root(&context)?;
Ok(pixmap)
}

View File

@ -1,121 +0,0 @@
use cosmic_text::{
Align, Attrs, AttrsList, Buffer, BufferLine, Color, FontSystem, LineEnding, Metrics, Shaping,
SwashCache,
};
use tiny_skia::{Paint, Pixmap, Rect, Transform};
pub struct FontRenderer {
font_system: FontSystem,
scale_factor: f32,
metrics: Metrics,
}
impl FontRenderer {
pub fn new(
font_size: f32,
line_height: f32,
scale_factor: f32,
fonts_folder: &str,
) -> FontRenderer {
let mut font_system = FontSystem::new();
font_system.db_mut().load_fonts_dir(fonts_folder);
let metrics = Metrics::new(font_size, line_height).scale(scale_factor.clone());
FontRenderer {
metrics,
font_system,
scale_factor,
}
}
pub fn draw_text(
&mut self,
x: f32,
y: f32,
w: f32,
h: f32,
spans: Vec<(&str, Attrs)>,
pixmap: &mut Pixmap,
) {
let mut buffer = Buffer::new(&mut self.font_system, self.metrics);
buffer.set_size(
&mut self.font_system,
Some(w * self.scale_factor),
Some(h * self.scale_factor),
);
buffer.set_rich_text(
&mut self.font_system,
spans,
Attrs::new(),
Shaping::Advanced,
);
self.draw(x, y, &mut buffer, pixmap);
}
pub fn draw_line(
&mut self,
x: f32,
y: f32,
w: f32,
h: f32,
line: &str,
attrs: Attrs,
align: Option<Align>,
pixmap: &mut Pixmap,
) {
let mut buffer = Buffer::new(&mut self.font_system, self.metrics);
let mut line = if cfg!(unix) {
BufferLine::new(
line,
LineEnding::Lf,
AttrsList::new(attrs),
Shaping::Advanced,
)
} else if cfg!(windows) {
BufferLine::new(
line,
LineEnding::CrLf,
AttrsList::new(attrs),
Shaping::Advanced,
)
} else {
panic!("Unsupported OS")
};
line.set_align(align);
buffer.lines = vec![line];
buffer.set_size(&mut self.font_system, Some(w), Some(h));
self.draw(x, y, &mut buffer, pixmap);
}
fn draw<'a>(&mut self, x: f32, y: f32, buffer: &mut Buffer, pixmap: &mut Pixmap) {
let mut swash_cache = SwashCache::new();
let default_font_color = Color::rgb(255, 255, 255);
buffer.draw(
&mut self.font_system,
&mut swash_cache,
default_font_color,
|font_x, font_y, w, h, color| {
let mut paint = Paint {
anti_alias: true,
..Default::default()
};
paint.set_color_rgba8(color.r(), color.g(), color.b(), color.a());
let rect = Rect::from_xywh(
font_x as f32 + x * self.scale_factor,
font_y as f32 + y * self.scale_factor,
w as f32,
h as f32,
)
.expect("Cannot draw text on pixmap");
pixmap.fill_rect(rect, &paint, Transform::identity(), None);
},
);
}
}

61
lua/codesnap/client.lua Normal file
View File

@ -0,0 +1,61 @@
local logger = require("codesnap.utils.logger")
local static = require("codesnap.static")
local client = {
job_id = 0,
}
local cwd = static.cwd .. "/snap-server"
function client:connect()
return vim.fn.jobstart({
cwd .. "/target/release/snap-server",
}, {
cwd = cwd,
stderr_buffered = true,
rpc = true,
on_stderr = function(_, err)
vim.fn.jobstop(self.job_id)
logger.error(err)
end,
on_exit = function()
vim.fn.chanclose(self.job_id)
self.job_id = 0
end,
})
end
function client:init()
return self.job_id == 0 and client:connect() or self.job_id
end
function client:start()
self.job_id = client:init()
if self.job_id == 0 then
logger.error("cannot start rpc process")
return
end
if self.job_id == -1 then
logger.error("rpc process is not executable")
vim.fn.jobstop(self.job_id)
return
end
return self
end
function client:send(event, message)
vim.fn.rpcnotify(self.job_id, event, message)
end
function client:stop()
if self.job_id == 0 or self.job_id == -1 then
return
end
vim.fn.jobstop(self.job_id)
end
return client

View File

@ -1,59 +0,0 @@
local visual_utils = require("codesnap.utils.visual")
local path_utils = require("codesnap.utils.path")
local string_utils = require("codesnap.utils.string")
local static = require("codesnap.static")
local table_utils = require("codesnap.utils.table")
local config_module = {}
local assets_folder = static.cwd .. "/assets"
-- Auto generated codesnap filename based on the following rule:
-- CodeSnap_y-m-d_at_h:m:s
local function auto_generate_snap_filename()
return os.date("CodeSnap_%Y-%m-%d_at_%H:%M:%S.png")
end
-- If the save_path is already configured, but no explicit filename is specified,
-- it will be replaced with auto-generated filename
local function parse_save_path(save_path)
if save_path == nil or string_utils.ends_with(save_path, "png") then
return save_path
end
local parsed_save_path = string_utils.ends_with(save_path, "/") and save_path or save_path .. "/"
return parsed_save_path .. auto_generate_snap_filename()
end
local function get_file_path(show_workspace)
local relative_path = path_utils.get_relative_path()
return show_workspace and path_utils.get_workspace() .. "/" .. relative_path or relative_path
end
function config_module.get_config(extension)
local code = visual_utils.get_selected_text()
local start_line_number = visual_utils.get_start_line_number()
if string_utils.is_str_empty(code) then
error("No code is selected", 0)
return
end
local config = table_utils.merge({
code = code,
extension = extension,
code_file_path = vim.fn.expand("%:p"),
fonts_folder = assets_folder .. "/fonts",
themes_folder = assets_folder .. "/themes",
theme = "base16-onedark",
file_path = static.config.has_breadcrumbs and get_file_path(static.config.show_workspace) or "",
start_line_number = static.config.has_line_number and start_line_number or nil,
}, static.config)
config.save_path = parse_save_path(config.save_path)
return config
end
return config_module

View File

@ -1,55 +0,0 @@
local string_utils = require("codesnap.utils.string")
local table_utils = require("codesnap.utils.table")
local highlight_module = {}
function highlight_module.call_cb_with_parsed_config(cb_name, highlight_start_line_number, highlight_end_line_number)
vim.api.nvim_buf_delete(0, {})
vim.schedule(function()
local main = require("codesnap")
local config = table_utils.merge(main.highlight_mode_config, {
highlight_start_line_number = highlight_start_line_number,
highlight_end_line_number = highlight_end_line_number,
})
main[cb_name](config)
end)
end
function highlight_module.create_highlight_selector_window(cb_name, code)
local width = 100
local height = #code + 2
local row = vim.fn.winheight(0) / 2 - height / 2
local col = vim.fn.winwidth(0) / 2 - width / 2
local bufnr = vim.api.nvim_create_buf(false, true)
vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, code)
local window_id = vim.api.nvim_open_win(bufnr, false, {
relative = "editor",
width = width,
height = height,
col = col,
row = row,
style = "minimal",
border = "rounded",
title = "Select highlight lines",
title_pos = "center",
})
vim.api.nvim_buf_set_option(bufnr, "modifiable", false)
vim.api.nvim_buf_set_option(bufnr, "filetype", vim.bo.filetype)
vim.api.nvim_buf_set_keymap(bufnr, "n", "q", ":q<CR>", {})
vim.api.nvim_buf_set_keymap(bufnr, "", "<ESC>", ":q<CR>", {})
vim.api.nvim_buf_set_keymap(
bufnr,
"v",
"<CR>",
":lua require('codesnap.highlight').call_cb_with_parsed_config('"
.. cb_name
.. "', require('codesnap.utils.visual').get_start_line_number(), require('codesnap.utils.visual').get_end_line_number())<CR>",
{ silent = true }
)
vim.api.nvim_set_current_win(window_id)
end
return highlight_module

View File

@ -1,76 +1,33 @@
local static = require("codesnap.static")
local visual_utils = require("codesnap.utils.visual")
local table_utils = require("codesnap.utils.table")
local string_utils = require("codesnap.utils.string")
local config_module = require("codesnap.config")
local highlight_module = require("codesnap.highlight")
local static = require("codesnap.static")
local client = require("codesnap.client")
local visual_utils = require("codesnap.utils.visual")
local main = {
cwd = static.cwd,
preview_switch = static.preview_switch,
highlight_mode_config = nil,
}
function main.setup(config)
static.config = table_utils.merge(static.config, config == nil and {} or config)
end
function main.copy_into_clipboard_with_config(config)
require("generator").copy_into_clipboard(config)
vim.cmd("delmarks <>")
vim.notify("Save snapshot into clipboard successfully")
end
-- Take ASCII code snapshot into clipboard
function main.copy_ascii_snapshot(extension)
require("generator").copy_ascii(config_module.get_config(extension))
vim.cmd("delmarks <>")
vim.notify("Save snapshot into clipboard successfully")
end
function main.save_snapshot_with_config(config)
if string_utils.is_str_empty(static.config.save_path) then
error(
"If you want to save snapshot in somewhere, you should config the save_path before, refer: https://github.com/mistricky/codesnap.nvim?tab=readme-ov-file#save-the-snapshot",
0
)
if static.config.auto_load then
client:start()
end
local matched_extension = string.match(static.config.save_path, "%.(.+)$")
if matched_extension ~= "png" and matched_extension ~= nil then
error("The extension of save_path should be .png", 0)
end
require("generator").save_snapshot(config)
vim.cmd("delmarks <>")
---@diagnostic disable-next-line: need-check-nil
vim.notify("Save snapshot in " .. config.save_path .. " successfully")
client:send("config_setup", static.config)
end
-- Take a snapshot and copy it into clipboard
function main.copy_into_clipboard(extension)
main.copy_into_clipboard_with_config(config_module.get_config(extension))
function main.preview_code()
client:send("preview_code", { content = visual_utils.get_selected_text(), language = vim.bo.filetype })
end
-- Take a snapshot and save it into the specified path
function main.save_snapshot(extension)
main.save_snapshot_with_config(config_module.get_config(extension))
function main.open_preview()
client:send("open_preview")
end
function main.highlight_mode_copy_into_clipboard(extension)
main.highlight_mode_config = config_module.get_config(extension)
highlight_module.create_highlight_selector_window(
"copy_into_clipboard_with_config",
visual_utils.get_selected_lines()
)
end
function main.highlight_mode_save_snapshot(extension)
main.highlight_mode_config = config_module.get_config(extension)
highlight_module.create_highlight_selector_window("save_snapshot_with_config", visual_utils.get_selected_lines())
function main.stop_client()
client:stop()
end
return main

View File

@ -3,19 +3,13 @@ local path_utils = require("codesnap.utils.path")
return {
config = {
mac_window_bar = true,
title = "CodeSnap.nvim",
code_font_family = "CaskaydiaCove Nerd Font",
watermark_font_family = "Pacifico",
opacity = true,
watermark = "CodeSnap.nvim",
bg_theme = "default",
breadcrumbs_separator = "/",
has_breadcrumbs = false,
has_line_number = false,
show_workspace = false,
min_width = 0,
bg_x_padding = 122,
bg_y_padding = 82,
save_path = path_utils.get_default_save_path(),
preview_title = "CodeSnap.nvim",
editor_font_family = "CaskaydiaCove Nerd Font",
watermark_font_family = "Pacifico",
highlight_theme = "atom-one-dark",
auto_load = true,
},
cwd = path_utils.back(path_utils.back(debug.getinfo(1, "S").source:sub(2):match("(.*[/\\])"))),
preview_switch = true,

View File

@ -0,0 +1,11 @@
local logger = {}
function logger.log(level, message)
vim.api.nvim_notify("[" .. level .. "] CodeSnap: " .. tostring(vim.inspect(message)), vim.log.levels[level], {})
end
function logger.error(message)
logger.log("ERROR", message)
end
return logger

View File

@ -1,47 +1,9 @@
local string_utils = require("codesnap.utils.string")
local platform_utils = require("codesnap.utils.platform")
local path_utils = {}
function path_utils.get_escaped_cwd()
local cwd = vim.fn.getcwd()
return string_utils.escape(cwd)
end
function path_utils.back(path)
local parsed_path, _ = path:gsub("/[^\\/]+/?$", "")
return parsed_path
end
function path_utils.get_workspace()
local cwd = vim.fn.getcwd()
local _, _, workspace = string.find(cwd, "/([^/]+)$")
return workspace == nil and "" or workspace
end
function path_utils.get_relative_path()
local full_file_path = vim.fn.expand("%:p")
return full_file_path:gsub(path_utils.get_escaped_cwd(), ""):sub(2)
end
-- Get default save path by OS
-- If Linux, use XDG_PICTURE_DIR
-- if mac use ~/Pictures
-- if windows use FOLDERID_Pictures (If support is added back)
function path_utils.get_default_save_path()
local home_picture_folder = os.getenv("HOME") .. "/Pictures"
return platform_utils.match_os({
Darwin = function()
return home_picture_folder
end,
Linux = function()
return os.getenv("XDG_PICTURES_DIR") or home_picture_folder
end,
})
end
return path_utils

View File

@ -1,15 +0,0 @@
local platform_utils = {}
local current_os_name = vim.loop.os_uname().sysname
function platform_utils.match_os(matches_table)
local fn = matches_table[current_os_name]
if fn == nil then
error("codesnap.nvim not supported on " .. current_os_name)
end
return fn()
end
return platform_utils

View File

@ -12,26 +12,4 @@ function string_util.ends_with(str, suffix)
return str:sub(-#suffix) == suffix
end
function string_util.is_str_empty(target)
return target == nil or target == ""
end
function string_util.convert_empty_to_nil(target)
if target == "" then
return nil
else
return target
end
end
function string_util.split(str, delimiter)
local result = {}
for token in string.gmatch(str, "[^" .. delimiter .. "]+") do
table.insert(result, token)
end
return result
end
return string_util

View File

@ -33,7 +33,7 @@ end
function table_utils.serialize_array(t)
local result = list_utils.map(t, function(ele)
table_utils.to_string(ele)
table_utils.serialize_json(ele)
end)
return "[" .. result.concat(t, ",") .. "]"
@ -43,17 +43,17 @@ function table_utils.serialize_table(t)
local result = {}
for key, value in pairs(t) do
table.insert(result, string.format("%s = %s", key, table_utils.to_string(value)))
table.insert(result, string.format('"%s":%s', key, table_utils.serialize_json(value)))
end
return "{" .. table.concat(result, ",") .. "}"
end
function table_utils.serialize_string(value)
return "[[" .. value .. "]]"
return '"' .. value .. '"'
end
function table_utils.to_string(t)
function table_utils.serialize_json(t)
local complex_type_parser = {
array = table_utils.serialize_array,
table = table_utils.serialize_table,
@ -67,14 +67,4 @@ function table_utils.to_string(t)
return parse(t)
end
-- function table_utils.to_string(t)
-- local result = ""
--
-- for key, value in pairs(t) do
-- result = result .. key .. ":" .. tostring(value) .. ","
-- end
--
-- return "{" .. result .. "}"
-- end
return table_utils

View File

@ -1,36 +1,6 @@
local visual_utils = {}
-- Get all the lines from "from" to "to" and return them as a single string
-- If "from" and "to" are the same, return the line at "from"
local function get_whole_lines(from, to)
local lines = {}
if from == to then
table.insert(lines, vim.api.nvim_buf_get_lines(0, from - 1, from, false)[1])
else
for i = from, to do
table.insert(lines, vim.api.nvim_buf_get_lines(0, i - 1, i, false)[1])
end
end
return table.concat(lines, "\n")
end
function visual_utils.get_start_line_number()
return vim.fn.line("'<")
end
function visual_utils.get_end_line_number()
return vim.fn.line("'>")
end
function visual_utils.get_selected_lines()
return vim.fn.getline("'<", "'>")
end
function visual_utils.get_selected_text()
return table.concat(visual_utils.get_selected_lines(), "\n")
end
function visual_utils.get_selected_text_realtime()
local start_pos = vim.fn.getpos("v")
local end_pos = vim.fn.getpos(".")
@ -40,14 +10,9 @@ function visual_utils.get_selected_text_realtime()
start_pos, end_pos = end_pos, start_pos
end
if vim.api.nvim_get_mode().mode == "V" then
return get_whole_lines(start_pos[2], end_pos[2])
end
if start_pos[2] == end_pos[2] then
return vim.api.nvim_buf_get_lines(0, start_pos[2] - 1, start_pos[2], false)[1]:sub(start_pos[3], end_pos[3] - 1)
end
else
local selected_text = {}
for i = start_pos[2], end_pos[2] do
local line_text = vim.api.nvim_buf_get_lines(0, i - 1, i, false)[1]
@ -60,8 +25,8 @@ function visual_utils.get_selected_text_realtime()
end
table.insert(selected_text, line_text)
end
return table.concat(selected_text, "\n")
end
end
return visual_utils

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -1,8 +1,14 @@
build:
./scripts/apply_generator.sh
make build_preview_client
make build_server
make make_static_files
build_generator_debug:
./scripts/build_generator.sh
build_preview_client:
cd snap-client && npm install && npm run build
build_generator:
./scripts/build_generator.sh --release
build_server:
cd snap-server && cargo build --release
make_static_files:
cp -r snap-client/build snap-server/public
cp -r snap-client/node_modules/highlight.js/styles/ snap-server/public/

View File

@ -1,42 +1,34 @@
local codesnap = require("codesnap")
-- local client = require("codesnap.client")
-- The func param is a function that come from rust side, the function
-- may raise exception to user side, the run_generator_function is used to
-- handle these function and print it friendly
local function run_generator_function(func)
xpcall(func, function(err)
print(err)
end)
end
-- vim.api.nvim_create_user_command("CodeSnap", function()
-- client:send("copy")
-- end, {})
local function take_snapshot(take_snapshot_function)
return function(detail)
local args = detail.fargs
vim.api.nvim_create_user_command("CodeSnapPreviewOn", function()
codesnap.open_preview()
end, {})
run_generator_function(function()
take_snapshot_function(args[1])
end)
local validModes = {
["v"] = true,
["V"] = true,
["^V"] = true,
}
vim.api.nvim_create_autocmd({ "CursorMoved" }, {
callback = function()
local mode = vim.api.nvim_get_mode().mode
if not validModes[mode] or not codesnap.preview_switch then
return
end
end
vim.api.nvim_create_user_command("CodeSnap", take_snapshot(codesnap.copy_into_clipboard), { nargs = "*", range = "%" })
codesnap.preview_code()
end,
})
vim.api.nvim_create_user_command("CodeSnapSave", take_snapshot(codesnap.save_snapshot), { nargs = "*", range = "%" })
vim.api.nvim_create_user_command(
"CodeSnapASCII",
take_snapshot(codesnap.copy_ascii_snapshot),
{ nargs = "*", range = "%" }
)
vim.api.nvim_create_user_command(
"CodeSnapHighlight",
take_snapshot(codesnap.highlight_mode_copy_into_clipboard),
{ nargs = "*", range = "%" }
)
vim.api.nvim_create_user_command(
"CodeSnapSaveHighlight",
take_snapshot(codesnap.highlight_mode_save_snapshot),
{ nargs = "*", range = "%" }
)
vim.api.nvim_create_autocmd({ "VimLeavePre" }, {
pattern = "*",
callback = function()
codesnap.stop_client()
end,
})

View File

@ -1,6 +1,6 @@
[project]
name = "codesnap.nvim"
version = "1.6.0"
version = "0.0.9"
description = "📸 Snapshot plugin that can make pretty code snapshots with real-time previews for Neovim"
author = "Mist"
email = "mist.zzh@gmail.com"

View File

@ -1,9 +0,0 @@
#!/usr/bin/env bash
source ./scripts/check_os.sh
function apply_generator {
cp -rf lua/"${os}generator.so" lua/generator.so
}
apply_generator $os

View File

@ -1,18 +0,0 @@
#!/usr/bin/env bash
source ./scripts/check_os.sh
(cd ./generator; cargo build $1)
lib_suffix="so"
target="debug"
if [[ $os =~ "mac" ]]; then
lib_suffix="dylib"
fi
if [[ $1 =~ "release" ]]; then
target="release"
fi
cp -rf ./generator/target/$target/libgenerator.$lib_suffix lua/generator.so

View File

@ -1,18 +0,0 @@
os="Unknown"
uname_output=`uname`
if [[ $uname_output == "Darwin" ]]; then
uname_m_output=`uname -m`
if [[ $uname_m_output == "arm64" ]]; then
os="mac-aarch64"
elif [[ $uname_m_output == "x86_64" ]]; then
os="mac-x86_64"
else
echo "Unknown sillicon"
fi
elif [[ $uname_output == "Linux" ]]; then
os="linux-x86_64"
else
echo "Unknown platform"
fi

23
snap-client/.gitignore vendored Normal file
View File

@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

46
snap-client/README.md Normal file
View File

@ -0,0 +1,46 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.\
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).

30957
snap-client/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

55
snap-client/package.json Normal file
View File

@ -0,0 +1,55 @@
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@tailwindcss/typography": "^0.5.10",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.5.2",
"@types/node": "^16.18.81",
"@types/react": "^18.2.55",
"@types/react-dom": "^18.2.19",
"downloadjs": "^1.4.7",
"highlight.js": "^11.9.0",
"html-to-image": "^1.11.11",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"react-use-websocket": "^3.0.0",
"typescript": "^4.9.5",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "npm run tailwindcss:compile && react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"tailwindcss:watch": "npm run tailwindcss:compile -- -w",
"tailwindcss:compile": "tailwindcss -i ./src/input.css -o ./src/output.css"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"@types/downloadjs": "^1.4.6",
"daisyui": "^3.9.4",
"tailwindcss": "^3.4.1"
}
}

View File

@ -0,0 +1,47 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<link rel="preconnect" href="https://fonts.googleapis.com" crossorigin="anonymous">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css2?family=Pacifico&display=swap" rel="stylesheet" crossorigin="anonymous">
<link rel="stylesheet" href="https://mshaugh.github.io/nerdfont-webfonts/build/caskaydiacove-nerd-font.css" crossorigin="anonymous">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

View File

@ -0,0 +1,15 @@
{
"short_name": "CdeoSnap.nvim",
"name": "CodeSnap.nvim",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

View File

@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

128
snap-client/src/app.tsx Normal file
View File

@ -0,0 +1,128 @@
import { useCallback, useEffect, useRef, useState } from "react";
import useWebSocket, { ReadyState } from "react-use-websocket";
import { ControlBar, Editor, Frame, Panel } from "./components";
import { useConfig, useEvent } from "./hooks";
import { toPng, toBlob } from "html-to-image";
import download from "downloadjs";
import { getWebsocketHost } from "./utils";
const CODE_EMPTY_PLACEHOLDER = `print "Hello, CodeSnap.nvim!"`;
const WATER_MARK_PLACEHOLDER = "CodeSnap.nvim";
const PREVIEW_TITLE_PLACEHOLDER = "CodeSnap.nvim";
const DEFAULT_THEME = "atom-one-dark";
function App() {
const [socketUrl] = useState(`ws://${getWebsocketHost()}/ws`);
const { sendMessage, lastMessage, readyState } = useWebSocket(socketUrl);
const event = useEvent(lastMessage);
const config = useConfig(event?.config_setup);
const frameRef = useRef<HTMLDivElement | null>(null);
const [isCopyButtonDisabled, setIsCopyButtonDisabled] = useState(false);
const handleCopyButtonClick = useCallback(async () => {
if (!frameRef.current) {
return;
}
setIsCopyButtonDisabled(true);
try {
const blob = await toBlob(frameRef.current);
const clipboardItem = new ClipboardItem({ "image/png": blob! });
navigator.clipboard.write([clipboardItem]);
} catch (e) {
console.error(e);
} finally {
setIsCopyButtonDisabled(false);
}
}, []);
const handleExportClick = useCallback(async () => {
if (!frameRef.current) {
return;
}
const dataURL = await toPng(frameRef.current);
download(dataURL, "codesnap.png");
}, []);
const notifyCopyCommand = useCallback(async () => {
if (!frameRef.current) {
return;
}
const dataURL = await toPng(frameRef.current);
sendMessage(dataURL);
}, [sendMessage]);
useEffect(() => {
if (readyState !== ReadyState.OPEN || !event?.copy) {
return;
}
notifyCopyCommand();
}, [event, readyState, notifyCopyCommand]);
useEffect(() => {
document.title = config?.preview_title ?? PREVIEW_TITLE_PLACEHOLDER;
}, []);
useEffect(() => {
const theme = config?.highlight_theme ?? DEFAULT_THEME;
const cssLink = document.createElement("link");
cssLink.rel = "stylesheet";
cssLink.href = `./styles/${theme}.css`;
document.head.appendChild(cssLink);
return () => {
document.head.removeChild(cssLink);
};
}
, [config?.highlight_theme]);
return (
<div className="w-full h-full flex flex-col items-center bg-deep-gray">
<p className="rainbow-text text-4xl font-extrabold mt-20">
CodeSnap.nvim
</p>
<Panel>
<ControlBar
isCopyButtonDisabled={isCopyButtonDisabled}
onExportClick={handleExportClick}
onCopyClick={handleCopyButtonClick}
readyState={readyState}
/>
<div id="frame" className="rounded-xl overflow-hidden">
<Frame
ref={frameRef}
watermarkFontFamily={config?.watermark_font_family}
watermark={config?.watermark ?? WATER_MARK_PLACEHOLDER}
>
<Editor
codeFontFamily={config?.editor_font_family}
language={event?.code?.language}
macStyleTitleBar={config?.mac_window_bar}
>
{event?.code?.content ?? CODE_EMPTY_PLACEHOLDER}
</Editor>
</Frame>
</div>
</Panel>
<a href="https://github.com/mistricky/codesnap.nvim">
<svg
role="img"
viewBox="0 0 24 24"
className="w-10 h-10 mt-10 fill-white opacity-50"
xmlns="http://www.w3.org/2000/svg"
>
<title>GitHub</title>
<path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12" />
</svg>
</a>
</div>
);
}
export default App;

View File

@ -0,0 +1,53 @@
import { useMemo } from "react";
import { ReadyState } from "react-use-websocket";
interface ConnectionStatusProps {
readyState: ReadyState;
}
const CONNECTION_STATUS_MAP = {
[ReadyState.CONNECTING]: {
text: "Connecting",
color: "#fdcb6e",
},
[ReadyState.OPEN]: {
text: "Connected",
color: "#00b894",
},
[ReadyState.CLOSING]: {
text: "Closing",
color: "#fab1a0",
},
[ReadyState.CLOSED]: {
text: "Closed",
color: "#636e72",
},
[ReadyState.UNINSTANTIATED]: {
text: "Uninstantiated",
color: "#2d3436",
},
} as const;
const UNKNOWN_STATE = { text: "Unknown", color: "#a29bfe" };
export const ConnectionStatus = ({ readyState }: ConnectionStatusProps) => {
const parsedState = useMemo(
() => CONNECTION_STATUS_MAP[readyState] ?? UNKNOWN_STATE,
[readyState],
);
return (
<div className="flex flex-grow flex-row items-center mr-1 ml-2">
<div
className="flex w-5 h-5 mr-2 justify-center items-center rounded-full"
style={{ backgroundColor: `${parsedState.color}50` }}
>
<div
className="w-3 h-3 rounded-full"
style={{ backgroundColor: parsedState.color }}
></div>
</div>
{parsedState.text}
</div>
);
};

View File

@ -0,0 +1,65 @@
import { ConnectionStatus } from "./connection-status";
import { ReadyState } from "react-use-websocket";
interface ControlBarProps {
isCopyButtonDisabled: boolean;
onCopyClick(): void;
onExportClick(): void;
readyState: ReadyState;
}
export const ControlBar = ({
onCopyClick,
onExportClick,
isCopyButtonDisabled,
readyState,
}: ControlBarProps) => {
return (
<div className="bg-neutral rounded-xl mb-2 p-1 flex flex-row items-center">
<ConnectionStatus readyState={readyState} />
<div className="flex flex-row items-center">
{/*
* <button className="btn mr-1">
<svg
role="img"
className="h-4 w-4 fill-neutral-500"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<title>X</title>
<path d="M18.901 1.153h3.68l-8.04 9.19L24 22.846h-7.406l-5.8-7.584-6.638 7.584H.474l8.6-9.83L0 1.154h7.594l5.243 6.932ZM17.61 20.644h2.039L6.486 3.24H4.298Z" />
</svg>
</button>
*/}
<button className="btn mr-1" onClick={onExportClick}>
Export
<svg
className="fill-neutral-content"
xmlns="http://www.w3.org/2000/svg"
height="24"
viewBox="0 -960 960 960"
width="24"
>
<path d="M480-320 280-520l56-58 104 104v-326h80v326l104-104 56 58-200 200ZM240-160q-33 0-56.5-23.5T160-240v-120h80v120h480v-120h80v120q0 33-23.5 56.5T720-160H240Z" />
</svg>
</button>
<button
onClick={onCopyClick}
id="copy"
className={`btn ${isCopyButtonDisabled && "btn-disabled"}`}
>
Copy
<svg
className="fill-neutral-content"
xmlns="http://www.w3.org/2000/svg"
height="20"
viewBox="0 -960 960 960"
width="20"
>
<path d="M360-240q-33 0-56.5-23.5T280-320v-480q0-33 23.5-56.5T360-880h360q33 0 56.5 23.5T800-800v480q0 33-23.5 56.5T720-240H360Zm0-80h360v-480H360v480ZM200-80q-33 0-56.5-23.5T120-160v-560h80v560h440v80H200Zm160-240v-480 480Z" />
</svg>{" "}
</button>
</div>
</div>
);
};

View File

@ -0,0 +1 @@
export * from "./control-bar";

View File

@ -0,0 +1,53 @@
import { MacStyleTitleBar } from "./mac-style-titlebar";
import hljs from "highlight.js";
export interface EditorProps {
macStyleTitleBar?: boolean;
language?: string;
opacity?: boolean;
codeFontFamily?: string;
children: string;
}
const DEFAULT_CODE_FONT_FAMILY = "CaskaydiaCove Nerd Font";
const LSP_LANGUAGE_NAME_MAP: Record<string, string> = {
typescriptreact: "tsx",
javascriptreact: "jsx",
};
const highlightLanguage = (code: string, language?: string) => {
if (!language) {
return hljs.highlightAuto(code).value;
}
try {
return hljs.highlight(code, {
language: LSP_LANGUAGE_NAME_MAP[language] ?? language,
}).value;
} catch {
return hljs.highlightAuto(code).value;
}
};
export const Editor = ({
children,
language,
codeFontFamily,
opacity = true,
macStyleTitleBar = true,
}: EditorProps) => (
<div
className={`editor-shadow ${opacity ? "bg-one-dark-base/[.93]" : "bg-one-dark-base"} rounded-2xl p-5 pb-7 border-border-color border-[1px]`}
>
{macStyleTitleBar && <MacStyleTitleBar />}
<pre className="mt-4">
<code
className="code"
style={{ fontFamily: codeFontFamily ?? DEFAULT_CODE_FONT_FAMILY }}
dangerouslySetInnerHTML={{
__html: highlightLanguage(children, language),
}}
/>
</pre>
</div>
);

View File

@ -0,0 +1,26 @@
import { forwardRef, PropsWithChildren } from "react";
const DEFAULT_WATERMARK_FONT_FAMILY = "Pacifico";
export interface FrameProps {
watermark?: string;
watermarkFontFamily?: string;
}
export const Frame = forwardRef<HTMLDivElement, PropsWithChildren<FrameProps>>(
({ children, watermark, watermarkFontFamily }, ref) => (
<div ref={ref} className="bg-relay min-w-[800px] p-20">
{children}
{watermark && (
<p
style={{
fontFamily: watermarkFontFamily ?? DEFAULT_WATERMARK_FONT_FAMILY,
}}
className="text-xl opacity-50 font-bold text-white text-center w-full mt-14"
>
{watermark}
</p>
)}
</div>
),
);

View File

@ -0,0 +1,2 @@
export * from "./frame";
export * from "./editor";

View File

@ -0,0 +1,18 @@
interface ButtonProps {
color: string;
}
const Button = ({ color }: ButtonProps) => (
<div
className="w-4 h-4 mr-2 rounded-full"
style={{ backgroundColor: color }}
></div>
);
export const MacStyleTitleBar = () => (
<div className="flex flex-row">
<Button color="#FF5E57" />
<Button color="#FFBC2E" />
<Button color="#2BC841" />
</div>
);

View File

@ -0,0 +1,3 @@
export * from "./control-bar";
export * from "./panel";
export * from "./editor";

View File

@ -0,0 +1,7 @@
import { PropsWithChildren } from "react";
export interface PanelProps {}
export const Panel = ({ children }: PropsWithChildren<PanelProps>) => (
<div className="p-10 br-10">{children}</div>
);

View File

@ -0,0 +1,3 @@
export * from "./use-event";
export * from "./use-storage";
export * from "./use-config";

View File

@ -0,0 +1,20 @@
import { useLocalStorage } from "./use-storage";
export interface Config {
mac_window_bar: boolean;
opacity: boolean;
watermark: string;
auto_load: boolean;
preview_title: string;
watermark_font_family: string;
editor_font_family: string;
highlight_theme: string;
}
const CONFIG_STORAGE_KEY = "CONFIG_STORAGE_KEY";
export const useConfig = (defaultConfig?: Config) => {
const [config] = useLocalStorage(CONFIG_STORAGE_KEY, defaultConfig);
return config;
};

View File

@ -0,0 +1,34 @@
import { useMemo } from "react";
import { Config } from "./use-config";
export enum EventType {
CONFIG_SETUP = "config_setup",
CODE = "code",
COPY = "copy",
}
type CodeMessage = {
content: string;
language: string;
};
type ParsedConfig = {
[EventType.CODE]: CodeMessage;
[EventType.CONFIG_SETUP]: Config;
[EventType.COPY]: undefined;
};
export const useEvent = (
event: MessageEvent<string> | null,
): Partial<ParsedConfig> | undefined =>
useMemo(() => {
if (!event) {
return undefined;
}
const parsedEvent = JSON.parse(event.data);
return {
[parsedEvent.name]: parsedEvent.data,
};
}, [event]);

View File

@ -0,0 +1,33 @@
import { useCallback, useMemo } from "react";
const createStorageHook =
(storage: Storage) =>
<T>(
key: string,
defaultData?: T,
): [NonNullable<T> | null, (value: T) => void] => {
const setValue = useCallback(
(value: T) => {
storage.setItem(key, JSON.stringify(value));
},
[key],
);
const value = useMemo(() => {
const value = storage.getItem(key);
if (defaultData) {
setValue(defaultData);
return defaultData;
}
return value ? JSON.parse(value) : value;
}, [key, defaultData, setValue]);
return [value, setValue];
};
export const useLocalStorage = createStorageHook(localStorage);
export const useSessionStorage = createStorageHook(sessionStorage);

19
snap-client/src/index.tsx Normal file
View File

@ -0,0 +1,19 @@
import React from "react";
import ReactDOM from "react-dom/client";
import "./output.css";
import App from "./app";
import reportWebVitals from "./reportWebVitals";
const root = ReactDOM.createRoot(
document.getElementById("root") as HTMLElement,
);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>,
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

106
snap-client/src/input.css Normal file
View File

@ -0,0 +1,106 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
html, body, #root {
height: 100%;
background-image:
linear-gradient(to right, rgba(36, 46, 54, 0.2) 2px, transparent 1px),
linear-gradient(to bottom, rgba(36, 46, 54, 0.2) 2px, transparent 1px);
background-size: 2.5rem 2.5rem;
background-position: center center;
}
@layer components {
.rainbow-text {
background-image: linear-gradient(90deg,hsl(var(--s)) 4%,color-mix(in oklch, hsl(var(--sf)), hsl(163.22deg 80% 43%)));
-webkit-text-fill-color: transparent;
background-clip: text;
}
.editor-shadow {
box-shadow: 0 20px 68px rgba(0, 0, 0, 0.55);
}
.pacifico-regular {
font-family: "Pacifico", cursive;
font-weight: 400;
font-style: normal;
}
.bg-stripe {
background: linear-gradient(to right, #1fa2ff, #12d8fa, #a6ffcb);
}
.bg-flare {
background: linear-gradient(to right, #f12711, #f5af19);
}
.bg-vanusa {
background: linear-gradient(to right, #da4453, #89216b);
}
.bg-sublime-light {
background: linear-gradient(to right, #fc5c7d, #6a82fb);
}
.bg-bighead {
background: linear-gradient(to right, #c94b4b, #4b134f);
}
.bg-velvet-sun {
background: linear-gradient(to right, #e1eec3, #f05053);
}
.bg-argon {
background: linear-gradient(to right, #03001e, #7303c0, #ec38bc, #fdeff9);
}
.bg-celestial {
background: linear-gradient(to right, #c33764, #1d2671);
}
.bg-relay {
background: linear-gradient(to right, #3a1c71, #d76d77, #ffaf7b);
}
.bg-crystal-clear {
background: linear-gradient(to right, #159957, #155799);
}
.bg-ibiza-sunset {
background: linear-gradient(to right, #ee0979, #ff6a00);
}
.bg-fresh-turboscent {
background: linear-gradient(to right, #f1f2b5, #135058);
}
.bg-cheer-up-emo-kid {
background: linear-gradient(to right, #556270, #ff6b6b);
}
.bg-starfall {
background: linear-gradient(to right, #f0c27b, #4b1248);
}
.bg-nelson {
background: linear-gradient(to right, #f2709c, #ff9472);
}
.bg-forever-lost {
background: linear-gradient(to right, #5d4157, #a8caba);
}
.bg-blurry-beach {
background: linear-gradient(to right, #d53369, #cbad6d);
}
.bg-influenza {
background: linear-gradient(to right, #c04848, #480048);
}
.bg-jshine {
background: linear-gradient(to right, #12c2e9, #c471ed, #f64f59);
}
.bg-calm-darya {
background: linear-gradient(to right, #5f2c82, #49a09d);
}
.bg-titanium {
background: linear-gradient(to right, #283048, #859398);
}
.bg-pinky {
background: linear-gradient(to right, #dd5e89, #f7bb97);
}
.bg-purple-paradise {
background: linear-gradient(to right, #1d2b64, #f8cdda);
}
.bg-horizon {
background: linear-gradient(to right, #003973, #e5e5be);
}
.bg-noon-to-dusk {
background: linear-gradient(to right, #ff6e7f, #bfe9ff);
}
}

1
snap-client/src/react-app-env.d.ts vendored Normal file
View File

@ -0,0 +1 @@
/// <reference types="react-scripts" />

View File

@ -0,0 +1,15 @@
import { ReportHandler } from 'web-vitals';
const reportWebVitals = (onPerfEntry?: ReportHandler) => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
};
export default reportWebVitals;

View File

@ -0,0 +1,5 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';

View File

@ -0,0 +1,4 @@
export const getWebsocketHost = () =>
process.env.NODE_ENV === "development"
? "localhost:8080"
: window.location.host;

View File

@ -0,0 +1 @@
export * from "./addr";

View File

@ -0,0 +1,20 @@
import type { Config } from "tailwindcss";
export default {
content: ["./src/**/*.{js,jsx,ts,tsx}"],
plugins: [require("daisyui"), require("@tailwindcss/typography")],
daisyui: {
themes: ["dark"],
},
theme: {
fontFamily: {
caskaydiacove: "CaskaydiaCove Nerd Font",
},
extend: {
colors: {
"one-dark-base": "#282C34",
"border-color": "#545F64",
},
},
},
} satisfies Config;

26
snap-client/tsconfig.json Normal file
View File

@ -0,0 +1,26 @@
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src"
]
}

2550
snap-server/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

18
snap-server/Cargo.toml Normal file
View File

@ -0,0 +1,18 @@
[package]
name = "snap-server"
version = "0.1.0"
edition = "2021"
[dependencies]
actix = "0.13.3"
actix-files = "0.6.5"
actix-web = "4.5.1"
actix-web-actors = "4.3.0"
arboard = "3.3.1"
image = "0.24.8"
image-base64 = "0.1.0"
neovim-lib = "0.6.1"
rand = "0.8.5"
serde = {version = "1.0.196", features = ["derive", "serde_derive", "std"]}
serde_json = "1.0.113"
webbrowser = "0.8.12"

31
snap-server/src/event.rs Normal file
View File

@ -0,0 +1,31 @@
use serde::Serialize;
#[derive(Serialize)]
pub struct Event<T>
where
T: Serialize,
{
name: String,
data: T,
}
impl<T> Event<T>
where
T: Serialize,
{
pub fn new(name: &str, data: T) -> Event<T> {
Event {
name: name.to_string(),
data,
}
}
}
impl<T> Into<String> for Event<T>
where
T: Serialize,
{
fn into(self) -> String {
serde_json::to_string(&self).unwrap()
}
}

View File

@ -0,0 +1,71 @@
pub mod arguments;
pub mod config;
pub mod messages;
pub mod neovim;
use actix::{Actor, Addr, Context};
use arguments::parse_string_first;
pub use config::Config;
pub use messages::Message;
use neovim::Neovim;
use serde_json::Value;
use std::sync::{Arc, Mutex};
use crate::{
event::Event,
server::{ClientMessage, ConfigSetupMessage, Server},
};
pub struct EventHandler {
neovim: Arc<Mutex<Neovim>>,
server: Arc<Addr<Server>>,
port: u16,
}
impl Actor for EventHandler {
type Context = Context<Self>;
fn started(&mut self, _: &mut Self::Context) {
self.start_listen();
}
}
impl EventHandler {
pub fn new(neovim: Arc<Mutex<Neovim>>, server: Arc<Addr<Server>>, port: u16) -> EventHandler {
EventHandler {
neovim,
server,
port,
}
}
pub fn start_listen(&mut self) {
let receiver = self.neovim.lock().unwrap().create_receiver();
for (event_name, values) in receiver {
match Message::from(event_name.clone()) {
Message::OpenPreview => {
let _ = webbrowser::open(format!("http://localhost:{}", self.port).as_str());
}
// The Copy message is not implement yet, but will support in the future
Message::Copy => {}
Message::PreviewCode => self.server.do_send(ClientMessage {
msg: Event::new(
"code",
serde_json::from_str::<Value>(parse_string_first(&values).as_str())
.unwrap(),
)
.into(),
}),
Message::ConfigSetup => self.server.do_send(ConfigSetupMessage {
msg: parse_string_first(&values),
}),
Message::Unknown => self
.neovim
.lock()
.unwrap()
.print(&format!("Unhandled event which name is {}", &event_name)),
};
}
}
}

View File

@ -0,0 +1,9 @@
use neovim_lib::Value;
pub fn parse_string(values: &Vec<Value>) -> Vec<String> {
values.iter().map(|value| value.to_string()).collect()
}
pub fn parse_string_first(values: &Vec<Value>) -> String {
parse_string(values).first().unwrap().to_string()
}

Some files were not shown because too many files have changed in this diff Show More