1
0
Fork 0

[Release] v1.0.0 (#43)

* [Update] apply template

* [Feat] update assets files (#35)

* [Update] README add packer install config

* [Feat] take snapshot via skia engine

* [Feat] title component

* [Feat] add watermark

* [Feat] update padding of code panel

* [Remove] pack ci script

* [Release] v1.0.0

* [Update] apply template

* [Chore] remove unused code

* [Update] readme

* [Release] v1.0.1

* [Update] apply template

* [Update] readme

* Update README.md

* [Feat] compile nvim-0.9 FFI

* [Release] v1.0.2

* [Update] apply template

* [Update] README.md

* [Feat] add multi platform support

* [Feat] add workflow for build target binary package

* [Update] files based on generated files by template generator

* [Update] files based on generated files by template generator

* [Update] files based on generated files by template generator

* [Update] files based on generated files by template generator

* [Update] files based on generated files by template generator

* [Update] files based on generated files by template generator

* [Update] files based on generated files by template generator

* [Feat] build plugin after released

* [Delete] build.yml

* [Update] README

* [Release] v1.0.3

* [Update] README

* [Refactor] editor frame size calculation logic

* [Refactor] update margin of watermark

* [Feat] preset font family

* [Refactor] update component interface

* [Update] change theme to onedark

* [Refactor] redefine render_error and throw it to lua scope

* [Perf] build script

* [Refactor] abstract component concept & implement it for all widgets

* [Update] README.md

---------

Co-authored-by: mistricky <mistricky@users.noreply.github.com>
main
Mist 2024-03-17 01:07:12 +08:00 committed by GitHub
parent 53b3d2544a
commit 08f0b24cf4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
126 changed files with 3602 additions and 35200 deletions

11
.cargo/config Normal file
View File

@ -0,0 +1,11 @@
[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

@ -7,39 +7,67 @@ on:
branches:
- main
permissions:
contents: write
jobs:
pack:
runs-on: ubuntu-latest
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:
- name: Checkout
uses: actions/checkout@v4
- uses: actions/checkout@v3
- name: Setup nodejs
uses: actions/setup-node@v4
- name: Build library
uses: houseabsolute/actions-rust-cross@v0
with:
node-version: 20
cache: npm
cache-dependency-path: ./snap-client/package-lock.json
command: "build"
working-directory: ./generator
target: ${{ matrix.platform.target }}
toolchain: ${{ matrix.toolchain }}
args: "--release"
- name: Install deps
working-directory: snap-client
run: npm i
- name: Build package
working-directory: snap-client
run: npm run build
- name: Move into public folder
run: cp -r snap-client/build snap-server/public
- name: Rename dynamic lib
run: cp 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@v9
uses: EndBug/add-and-commit@v7
with:
message: "[Update] build newest client package"
message: '[Update] files based on generated files by template generator'
pull_strategy: 'NO-PULL'
push: false
- name: Push changes
run: |
git pull --rebase
git push
release:
needs: pack
runs-on: ubuntu-latest
needs: build
steps:
- name: Checkout
uses: actions/checkout@v4

1
.gitignore vendored
View File

@ -19,3 +19,4 @@ node_modules
# build
output.css
generator.so

View File

@ -1,4 +1,6 @@
![image](https://github.com/mistricky/codesnap.nvim/assets/22574136/c8982b8c-c273-4257-9fef-f0f9134fd9a1)
![image](https://github.com/mistricky/codesnap.nvim/assets/22574136/9c67eb33-a11c-4ce3-935d-3fb59ec5d015)
<p align="center">
<img src="https://img.shields.io/badge/Neovim-57A143?logo=neovim&logoColor=fff&style=for-the-badge" alt="Neovim" />
@ -14,37 +16,80 @@
<h1 align="center">CodeSnap.nvim</h1>
<p align="center">📸 Snapshot plugin that can make pretty code snapshots with real-time previews for Neovim</p>
> [!NOTE]
> This plugin is currently in its early stages and may have some bugs, please feel free to submit issues and PRs.
> [!WARNING]
> **v1.0.0** will bring some break changes
> - 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`
## ✨Features
- 🔥 Real-time preview
- 🤩 Beautiful code snap template
- 😎 Custom watermark and window style
- 💻 Mac style title bar
- 💻 Beautiful Mac-style title bar
- 🤖 Generate snapshots using only a single command
- 👏 [WIP] Custom template background
- 🤖 [WIP] Generate snapshot just one command
- 🔢 [WIP] Column number
- 🍞 [WIP] Breadcrumbs
## Prerequirements
- Rust environment required for compiling codesnap.nvim plugin server source code, visit [Install Rust](https://www.rust-lang.org/tools/install) for more detail.
- Neovim 9.0+
## Install
Recommend using [Lazy.nvim](https://github.com/folke/lazy.nvim) for installation, but you can still use another plugin manager you prefer.
**Lazy.nvim**
```lua
{ "mistricky/codesnap.nvim", build = "make" },
{ "mistricky/codesnap.nvim", build = "make", version = "^1" },
```
### Build manually
Since v0.0.1 was released, the CodeSnap.nvim will cross-compile for the following three targets, then the CodeSnap.nvim will automatically determine which package to use based on your system, you no longer need to have Rust environment if everything goes smoothly.
- x86_64-unknown-linux-gnu
- x86_64-apple-darwin
- aarch64-apple-darwin
If CodeSnap.nvim on your system still not works fine, there are a lot of reasons depending on your system arch or OS version, well you can try to build CodeSnap manually using the following config:
```lua
{ "mistricky/codesnap.nvim", build = "make build_generator", version = "^1" },
```
## Usage
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 :)
`CodeSnap.nvim` provides the following two ways to take snapshots of currently selected code
https://github.com/mistricky/codesnap.nvim/assets/22574136/5e1a023e-142f-49e8-b24f-707da3728fd5
### 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/88d9fe9e-d938-4d82-a1e4-b7170ca47dd9
### 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({
-- ...
save_path: ...
})
```
https://github.com/mistricky/codesnap.nvim/assets/22574136/7b156a89-1e0d-48cd-b062-af5a460973ba
## Watermark
Watermark is something that makes screenshots more personalized, but if you don't like watermark just set it as empty string to hide it.
```lua
require("codesnap").setup({
-- ...
watermark: ""
})
```
## Commands
```shell
CodeSnapPreviewOn # Open preview page
CodeSnap # Take a snapshot of the currently selected code and copy the snapshot into the clipboard
-- The following commands are planned but not implemented yet. (welcome PR :))
CodeSnap # Take a code snap and copy it into the clipboard
CodeSnapSave # Save the snapshot of the currently selected code and save it on the disk
```
## Configuration
@ -56,12 +101,11 @@ require("codesnap").setup({...})
There is a default config:
```lua
{
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
mac_window_bar = true,
title = "CodeSnap.nvim",
code_font_family = "CaskaydiaCove Nerd Font",
watermark_font_family = "Pacifico",
watermark = "CodeSnap.nvim",
}
```

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,560 @@
<?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: 0.0.11
version: 1.0.2

1429
generator/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

16
generator/Cargo.toml Normal file
View File

@ -0,0 +1,16 @@
[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.11.2"
serde = "1.0.197"
arboard = "3.3.2"
thiserror = "1.0.58"
[lib]
crate-type = ["cdylib"]

24
generator/src/code.rs Normal file
View File

@ -0,0 +1,24 @@
const MIN_WIDTH: f32 = 100.;
fn min_width(width: f32) -> f32 {
if width < MIN_WIDTH {
MIN_WIDTH
} else {
width
}
}
pub fn calc_wh(text: &str, char_wdith: f32, line_height: f32) -> (f32, f32) {
let lines = 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;
(min_width(width), height)
}

View File

@ -0,0 +1,6 @@
pub mod background;
pub mod container;
pub mod editor;
pub mod interface;
pub mod rect;
pub mod watermark;

View File

@ -0,0 +1,68 @@
use tiny_skia::{
Color, GradientStop, LinearGradient, Paint, Pixmap, Point, Rect, SpreadMode, Transform,
};
use super::interface::{
component::{Component, ComponentContext, RenderParams},
render_error,
style::{ComponentAlign, ComponentStyle, RawComponentStyle},
};
pub struct Background {
children: Vec<Box<dyn Component>>,
gradient_stop_points: Vec<GradientStop>,
}
impl Background {
pub fn from_children(children: Vec<Box<dyn Component>>) -> Background {
Background {
children,
gradient_stop_points: 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(1.0, Color::from_rgba8(255, 175, 123, 255)),
],
}
}
}
impl Component for Background {
fn children(&self) -> &Vec<Box<dyn Component>> {
&self.children
}
fn style(&self) -> RawComponentStyle {
RawComponentStyle::default().align(ComponentAlign::Column)
}
fn draw_self(
&self,
pixmap: &mut Pixmap,
_context: &ComponentContext,
_render_params: &RenderParams,
_style: &ComponentStyle,
) -> render_error::Result<()> {
let mut paint = Paint::default();
let w = pixmap.width() as f32;
let h = pixmap.height() as f32;
paint.anti_alias = false;
paint.shader = LinearGradient::new(
Point::from_xy(0., 0.),
Point::from_xy(w, 0.),
self.gradient_stop_points.clone(),
SpreadMode::Pad,
Transform::identity(),
)
.unwrap();
pixmap.fill_rect(
Rect::from_xywh(0., 0., w, h).unwrap(),
&paint,
Transform::identity(),
None,
);
Ok(())
}
}

View File

@ -0,0 +1,53 @@
use tiny_skia::Pixmap;
use crate::edges::padding::Padding;
use super::interface::{
component::{Component, ComponentContext, ComponentRenderParams},
render_error::Result,
style::{RawComponentStyle, Style},
};
pub struct Container {
children: Vec<Box<dyn Component>>,
}
impl Component for Container {
fn children(&self) -> &Vec<Box<dyn Component>> {
&self.children
}
fn style(&self) -> RawComponentStyle {
Style::default().padding(Padding {
top: 82.,
left: 122.,
right: 122.,
bottom: 82.,
})
}
}
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

@ -0,0 +1,121 @@
pub mod code;
pub mod mac_title_bar;
use crate::edges::{edge::Edge, padding::Padding};
use self::{code::Code, mac_title_bar::MacTitleBar};
use super::{interface::component::Component, rect::Rect};
const CONTROL_BAR_RADIUS: f32 = 8.;
pub struct Editor {
x: f32,
y: f32,
w: f32,
h: f32,
children: Vec<Box<dyn Component>>,
has_title_bar: bool,
padding: Padding,
code_y_offset: f32,
}
impl Component for Editor {
fn children(&self) -> &Vec<Box<dyn Component>> {
&self.children
}
// fn get_children(&self) -> &Vec<Box<dyn Component>> {
// &self.children
// }
}
impl Editor {
pub fn new(x: f32, y: f32, w: f32, h: f32, has_title_bar: bool) -> Editor {
Editor {
x,
y,
w,
h,
has_title_bar,
padding: Padding {
left: 0.,
right: 0.,
top: 0.,
bottom: 0.,
},
children: vec![],
code_y_offset: 0.,
}
}
// pub fn render_mac_title_bar(mut self) -> Self {
// if self.has_title_bar {
// let mac_title_bar = MacTitleBar::from_xyr(
// self.x + CONTROL_BAR_RADIUS + self.padding.left,
// self.y + CONTROL_BAR_RADIUS + self.padding.top,
// CONTROL_BAR_RADIUS,
// );
//
// self.children.push(Box::new(mac_title_bar));
// }
//
// self
// }
// pub fn render_editor(mut self, radius: f32) -> Self {
// let roundrect = Rect::from_xywh(
// self.x,
// self.y,
// self.w + self.padding.horizontal(),
// self.h + self.header_height() + self.padding.vertical() + self.code_y_offset,
// )
// .radius(radius);
// self.children.push(Box::new(roundrect));
//
// self
// }
pub fn width(&self) -> f32 {
self.w + self.padding.horizontal()
}
pub fn height(&self) -> f32 {
self.h + self.header_height() + self.padding.vertical() + self.code_y_offset
}
pub fn header_height(&self) -> f32 {
if self.has_title_bar {
CONTROL_BAR_RADIUS * 2.
} else {
0.
}
}
// pub fn render_code(mut self, code: &str, line_height: f32, font_size: f32) -> Self {
// let code = Code::new(
// self.x + self.padding.left,
// self.y + self.header_height() + self.padding.top + self.code_y_offset,
// self.w,
// self.h,
// code.to_string(),
// )
// .line_height(line_height)
// .font_size(font_size);
//
// self.children.push(Box::new(code));
// self
// }
pub fn padding(mut self, padding: Padding) -> Self {
self.padding = padding;
self
}
pub fn code_y_offset(mut self, code_y_offset: f32) -> Self {
if self.has_title_bar {
self.code_y_offset = code_y_offset;
}
self
}
}

View File

@ -0,0 +1,80 @@
use crate::{
code::calc_wh,
components::interface::{
component::{Component, ComponentContext, RenderParams},
render_error,
style::{ComponentStyle, RawComponentStyle, Size, Style},
},
edges::margin::Margin,
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(&self.value, 9.05, self.line_height);
Style::default()
.size(Size::Num(w), Size::Num(h))
.margin(Margin {
top: 10.,
..Margin::default()
})
}
fn draw_self(
&self,
pixmap: &mut tiny_skia::Pixmap,
context: &ComponentContext,
render_params: &RenderParams,
style: &ComponentStyle,
) -> render_error::Result<()> {
let params = &context.take_snapshot_params;
let highlight = Highlight::new(
params.code.clone(),
params.code_font_family.clone(),
params.language.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,
line_height,
font_size,
children: vec![],
}
}
}

View File

@ -0,0 +1,94 @@
use tiny_skia::{Color, FillRule, Paint, PathBuilder, Transform};
use crate::components::interface::{
component::{Component, ComponentContext, RenderParams},
render_error,
style::{ComponentStyle, RawComponentStyle, Size, Style},
};
pub struct MacTitleBar {
radius: f32,
children: Vec<Box<dyn Component>>,
}
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))
}
fn draw_self(
&self,
pixmap: &mut tiny_skia::Pixmap,
context: &ComponentContext,
render_params: &RenderParams,
_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) -> MacTitleBar {
MacTitleBar {
radius,
children: vec![],
}
}
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

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

View File

@ -0,0 +1,170 @@
use std::sync::Arc;
use tiny_skia::Pixmap;
use crate::{
config::TakeSnapshotParams,
edges::{edge::Edge, padding::Padding},
};
use super::{
render_error,
style::{ComponentAlign, ComponentStyle, RawComponentStyle, Size, Style},
};
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()
}
fn draw_self(
&self,
_pixmap: &mut Pixmap,
_context: &ComponentContext,
_render_params: &RenderParams,
_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> {
let style = self.style();
let (width, height) = self.get_dynamic_wh();
Style {
width: self.parse_size(style.width, width)
+ style.padding.horizontal()
+ style.margin.horizontal(),
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,
sibling_style,
style.clone(),
),
);
self.draw_self(pixmap, context, &render_params, &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())
}
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 {
ComponentAlign::Row => calc_children_wh(|(w, h), child| {
let style = child.parsed_style();
(w + style.width, h.max(style.height))
}),
ComponentAlign::Column => calc_children_wh(|(w, h), child| {
let style = child.parsed_style();
(w.max(style.width), h + style.height)
}),
}
}
}

View File

@ -0,0 +1,19 @@
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("Find Highlight theme for {0} failed")]
HighlightCodeFailed(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

@ -0,0 +1,71 @@
use crate::edges::{margin::Margin, padding::Padding};
#[derive(Clone)]
pub enum ComponentAlign {
Row,
Column,
}
pub enum Size {
Dynamic,
Num(f32),
}
#[derive(Clone)]
pub struct Style<T> {
pub width: T,
pub height: T,
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 {
width: Size::Dynamic,
height: Size::Dynamic,
align: ComponentAlign::Row,
padding: Padding::default(),
margin: Margin::default(),
}
}
}
impl Default for ComponentStyle {
fn default() -> Self {
Style {
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
}
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

@ -0,0 +1,98 @@
use crate::edges::padding::Padding;
use super::interface::{
component::{Component, ComponentContext, RenderParams},
render_error,
style::{ComponentAlign, ComponentStyle, RawComponentStyle, Size, Style},
};
use tiny_skia::{FillRule, Paint, PathBuilder, Pixmap, Transform};
pub struct Rect {
radius: 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()
.align(ComponentAlign::Column)
.padding(Padding::from_value(20.))
}
fn draw_self(
&self,
pixmap: &mut Pixmap,
context: &ComponentContext,
render_params: &RenderParams,
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, children: Vec<Box<dyn Component>>) -> Rect {
Rect { radius, children }
}
}

View File

@ -0,0 +1,79 @@
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: Option<String>,
}
impl Component for Watermark {
fn draw_self(
&self,
pixmap: &mut Pixmap,
context: &ComponentContext,
render_params: &RenderParams,
_style: &ComponentStyle,
) -> render_error::Result<()> {
let params = &context.take_snapshot_params;
if let Some(value) = &params.watermark {
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,
&value,
attrs,
Some(Align::Center),
pixmap,
);
}
Ok(())
}
fn children(&self) -> &Vec<Box<dyn Component>> {
&self.children
}
fn style(&self) -> RawComponentStyle {
let default_style = RawComponentStyle::default();
if self.value.is_some() {
default_style.margin(Margin {
bottom: 22.,
top: 15.,
..Margin::default()
})
} else {
default_style
}
}
}
impl Watermark {
pub fn new(value: Option<String>) -> Watermark {
Watermark {
children: vec![],
value,
}
}
}

47
generator/src/config.rs Normal file
View File

@ -0,0 +1,47 @@
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 {
pub mac_window_bar: bool,
pub watermark: Option<String>,
pub title: Option<String>,
pub code_font_family: String,
pub watermark_font_family: String,
pub code: String,
pub language: Option<String>,
pub extension: Option<String>,
pub save_path: Option<String>,
pub themes_folder: String,
pub fonts_folder: String,
pub theme: String,
}
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)
}
}

31
generator/src/copy.rs Normal file
View File

@ -0,0 +1,31 @@
use crate::{config::TakeSnapshotParams, snapshot::take_snapshot};
use arboard::{Clipboard, ImageData};
use nvim_oxi::Result;
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 mut ctx = Clipboard::new().unwrap();
let img_data = ImageData {
width: pixmap.width() as usize,
height: pixmap.height() as usize,
bytes: colors.into(),
};
ctx.set_image(img_data).unwrap();
Ok(())
}

3
generator/src/edges.rs Normal file
View File

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

View File

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

View File

@ -0,0 +1,30 @@
use super::edge::Edge;
#[derive(Clone, Default)]
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 {
pub fn from_value(value: f32) -> Margin {
Margin {
left: value,
right: value,
top: value,
bottom: value,
}
}
}

View File

@ -0,0 +1,30 @@
use super::edge::Edge;
#[derive(Clone, Default)]
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

@ -0,0 +1,76 @@
use cosmic_text::{Attrs, Family, Style, Weight};
use syntect::{
easy::HighlightLines,
highlighting::{FontStyle, ThemeSet},
parsing::SyntaxSet,
util::LinesWithEndings,
};
use crate::components::interface::render_error::RenderError;
pub struct Highlight {
content: String,
language: Option<String>,
extension: Option<String>,
font_family: String,
}
pub type HighlightResult<'a> = Vec<(&'a str, Attrs<'a>)>;
impl Highlight {
pub fn new(
content: String,
font_family: String,
language: Option<String>,
extension: Option<String>,
) -> Highlight {
Highlight {
content,
language,
extension,
font_family,
}
}
pub fn parse(
&self,
theme_folder: &str,
theme: &str,
) -> Result<Vec<(&str, Attrs)>, RenderError> {
let syntax_set = SyntaxSet::load_defaults_newlines();
let theme_set = ThemeSet::load_from_folder(theme_folder)
.map_err(|_| RenderError::HighlightThemeLoadFailed)?;
let syntax = match &self.extension {
Some(extension) => syntax_set
.find_syntax_by_extension(extension)
.ok_or(RenderError::HighlightCodeFailed(extension.to_owned())),
None => {
let language = &self.language.clone().unwrap_or("Rust".to_string());
syntax_set
.find_syntax_by_name(language)
.ok_or(RenderError::HighlightCodeFailed(language.to_owned()))
}
}?;
let mut highlight = HighlightLines::new(syntax, &theme_set.themes[theme]);
let attrs = Attrs::new().family(Family::Name(self.font_family.as_ref()));
Ok(LinesWithEndings::from(&self.content)
.map(|line| highlight.highlight_line(line, &syntax_set).unwrap())
.fold(vec![], |acc, cur| [acc, cur].concat())
.into_iter()
.map(move |(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>())
}
}

24
generator/src/lib.rs Normal file
View File

@ -0,0 +1,24 @@
mod code;
mod components;
mod config;
mod copy;
mod edges;
mod highlight;
mod save;
mod snapshot;
mod text;
use copy::copy_into_clipboard;
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)),
]))
}

17
generator/src/save.rs Normal file
View File

@ -0,0 +1,17 @@
use crate::{config::TakeSnapshotParams, snapshot::take_snapshot};
use nvim_oxi::{lua, Result};
pub fn save_snapshot(config: TakeSnapshotParams) -> Result<()> {
match &config.save_path {
Some(path) => {
let pixmap = take_snapshot(config.clone())?;
pixmap
.save_png(path)
.map_err(|err| nvim_oxi::Error::Lua(lua::Error::RuntimeError(err.to_string())))
}
None => Err(nvim_oxi::Error::Lua(lua::Error::RuntimeError(
"Cannot find 'save_path' in config".to_string(),
))),
}
}

90
generator/src/snapshot.rs Normal file
View File

@ -0,0 +1,90 @@
use std::sync::Arc;
use tiny_skia::Pixmap;
use crate::components::background::Background;
use crate::components::container::Container;
use crate::components::editor::code::Code;
use crate::components::editor::mac_title_bar::MacTitleBar;
// use crate::components::editor::mac_title_bar::MacTitleBar;
use crate::components::interface::render_error;
use crate::components::rect::Rect;
use crate::components::watermark::Watermark;
// use crate::components::watermark::Watermark;
use crate::config::TakeSnapshotParams;
use crate::{
code::calc_wh,
components::interface::component::{Component, ComponentContext},
};
// Scale the screenshot to 3 times its size
const SCALE_FACTOR: f32 = 3.;
// The params is come from neovim instance
pub fn take_snapshot(params: TakeSnapshotParams) -> render_error::Result<Pixmap> {
// let (width, height) = calc_wh(&params.code, 9.05, 20.);
// let pixmap_vertical_padding = 82.;
// let pixmap_horizontal_padding = 122.;
// // Padding of editor shape
// let padding = Padding {
// left: 20.,
// right: 20.,
// top: 20.,
// bottom: 24.,
// };
// let editor = Editor::new(
// pixmap_horizontal_padding,
// pixmap_vertical_padding,
// width,
// height,
// params.mac_window_bar,
// )
// .code_y_offset(15.)
// .padding(padding.clone())
// .render_editor(16.)
// .render_mac_title_bar()
// .render_code(&params.code, 20., 15.);
// let pixmap_width = (pixmap_horizontal_padding * 2. + editor.width()) as u32;
// let pixmap_height = (pixmap_vertical_padding * 2. + editor.height()) as u32;
// let (watermark_bottom_margin, watermark_offset_y) = params
// .watermark
// .as_ref()
// .map(|_| (200., 40.))
// .unwrap_or((0., 0.));
//
// let mut pixmap = Pixmap::new(
// 0,
// 0, // pixmap_width * SCALE_FACTOR as u32,
// // (pixmap_height as f32 * SCALE_FACTOR + watermark_bottom_margin - watermark_offset_y) as u32,
// )
// .unwrap();
// .unwrap();
let context = ComponentContext {
scale_factor: SCALE_FACTOR,
take_snapshot_params: Arc::new(params.clone()),
};
// let watermark = Watermark::new(
// params.watermark,
// params.watermark_font_family,
// watermark_bottom_margin,
// );
// let background = Background::create().children(vec![Box::new(editor), Box::new(watermark)]);
//
// background.draw_root(&mut pixmap, &context)?;
//
let pixmap = Container::from_children(vec![Box::new(Background::from_children(vec![
Box::new(Rect::new(
16.,
vec![
Box::new(MacTitleBar::from_radius(8.)),
Box::new(Code::new(params.code, 20., 15.)),
],
)),
Box::new(Watermark::new(params.watermark)),
]))])
.draw_root(&context)?;
Ok(pixmap)
}

104
generator/src/text.rs Normal file
View File

@ -0,0 +1,104 @@
use cosmic_text::{
Align, Attrs, AttrsList, Buffer, BufferLine, Color, FontSystem, 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,
w * self.scale_factor,
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 = BufferLine::new(line, AttrsList::new(attrs), Shaping::Advanced);
line.set_align(align);
buffer.lines = vec![line];
buffer.set_size(&mut self.font_system, w, 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);
},
);
}
}

View File

@ -1,8 +1,18 @@
local table_utils = require("codesnap.utils.table")
local static = require("codesnap.static")
local client = require("codesnap.client")
local table_utils = require("codesnap.utils.table")
local generator = require("generator")
local string_utils = require("codesnap.utils.string")
local visual_utils = require("codesnap.utils.visual")
local assets_folder = static.cwd .. "/assets"
local function get_extension()
local file_path = vim.fn.expand("%:p")
local file_extension = string.match(file_path, "%.([^%.]+)$")
return file_extension
end
local main = {
cwd = static.cwd,
preview_switch = static.preview_switch,
@ -10,24 +20,43 @@ local main = {
function main.setup(config)
static.config = table_utils.merge(static.config, config == nil and {} or config)
end
if static.config.auto_load then
client:start()
local function get_config()
local code = visual_utils.get_selected_text()
local extension = get_extension()
if string_utils.is_str_empty(code) then
error("Please select code which you want to take snapshot first")
end
client:send("config_setup", static.config)
if string_utils.is_str_empty(extension) then
error("Cannot detect current filetype")
end
return table_utils.merge({
code = code,
extension = extension,
fonts_folder = assets_folder .. "/fonts",
themes_folder = assets_folder .. "/themes",
theme = "base16-onedark",
}, static.config)
end
function main.preview_code()
client:send("preview_code", { content = visual_utils.get_selected_text(), language = vim.bo.filetype })
function main.copy_into_clipboard()
generator.copy_into_clipboard(get_config())
vim.cmd("delmarks <>")
vim.notify("Save snapshot into clipboard successfully")
end
function main.open_preview()
client:send("open_preview")
end
function main.save_snapshot()
if string_utils.is_str_empty(static.config.save_path) then
error("Cannot find save_path from config")
end
function main.stop_client()
client:stop()
generator.save_snapshot(get_config())
vim.cmd("delmarks <>")
vim.notify("Save snapshot in " .. static.config.save_path .. " successfully")
end
return main

View File

@ -3,12 +3,10 @@ local path_utils = require("codesnap.utils.path")
return {
config = {
mac_window_bar = true,
opacity = true,
watermark = "CodeSnap.nvim",
preview_title = "CodeSnap.nvim",
editor_font_family = "CaskaydiaCove Nerd Font",
title = "CodeSnap.nvim",
code_font_family = "CaskaydiaCove Nerd Font",
watermark_font_family = "Pacifico",
auto_load = true,
watermark = "CodeSnap.nvim",
},
cwd = path_utils.back(path_utils.back(debug.getinfo(1, "S").source:sub(2):match("(.*[/\\])"))),
preview_switch = true,

View File

@ -12,4 +12,8 @@ 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
return string_util

View File

@ -16,6 +16,12 @@ local function get_whole_lines(from, to)
end
function visual_utils.get_selected_text()
local selected_text = vim.fn.getline("'<", "'>")
return table.concat(selected_text, "\n")
end
function visual_utils.get_selected_text_realtime()
local start_pos = vim.fn.getpos("v")
local end_pos = vim.fn.getpos(".")
@ -31,21 +37,22 @@ function visual_utils.get_selected_text()
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)
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]
if i == start_pos[2] then
line_text = line_text:sub(start_pos[3])
end
-- If select last line, there need to get column of current cursor
if i == end_pos[2] then
line_text = line_text:sub(1, end_pos[3] - 1)
end
table.insert(selected_text, line_text)
end
return table.concat(selected_text, "\n")
end
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]
if i == start_pos[2] then
line_text = line_text:sub(start_pos[3])
end
-- If select last line, there need to get column of current cursor
if i == end_pos[2] then
line_text = line_text:sub(1, end_pos[3] - 1)
end
table.insert(selected_text, line_text)
end
return table.concat(selected_text, "\n")
end
return visual_utils

BIN
lua/generator.so Executable file

Binary file not shown.

BIN
lua/linux-x86_64generator.so Executable file

Binary file not shown.

BIN
lua/mac-aarch64generator.so Executable file

Binary file not shown.

BIN
lua/mac-x86_64generator.so Executable file

Binary file not shown.

View File

@ -1,11 +1,9 @@
build:
make build_server
./scripts/apply_generator.sh
build_preview_client:
cd snap-client && npm install && npm run build
build_generator_debug:
./scripts/build_generator.sh
build_server:
cd snap-server && cargo build --release
make_static_files:
cp -r snap-client/build snap-server/public
build_generator:
./scripts/build_generator.sh --release
# cd generator && cargo build --release

View File

@ -1,33 +1,9 @@
local codesnap = require("codesnap")
-- local client = require("codesnap.client")
-- vim.api.nvim_create_user_command("CodeSnap", function()
-- client:send("copy")
-- end, {})
vim.api.nvim_create_user_command("CodeSnap", function()
codesnap.copy_into_clipboard()
end, { nargs = "*", range = "%" })
vim.api.nvim_create_user_command("CodeSnapPreviewOn", function()
codesnap.open_preview()
end, {})
local validModes = {
["v"] = true,
["V"] = true,
}
vim.api.nvim_create_autocmd({ "CursorMoved", "ModeChanged" }, {
callback = function()
local mode = vim.api.nvim_get_mode().mode
if not validModes[mode] or not codesnap.preview_switch then
return
end
codesnap.preview_code()
end,
})
vim.api.nvim_create_autocmd({ "VimLeavePre" }, {
pattern = "*",
callback = function()
codesnap.stop_client()
end,
})
vim.api.nvim_create_user_command("CodeSnapSave", function()
codesnap.save_snapshot()
end, { nargs = "*", range = "%" })

View File

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

11
scripts/apply_generator.sh Executable file
View File

@ -0,0 +1,11 @@
source ./scripts/check_os.sh
function apply_generator {
if [ -f lua/generator.so ]; then
rm lua/generator.so
fi
cp lua/"${1}generator.so" lua/generator.so
}
apply_generator $os

16
scripts/build_generator.sh Executable file
View File

@ -0,0 +1,16 @@
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

18
scripts/check_os.sh Normal file
View File

@ -0,0 +1,18 @@
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

View File

@ -1,23 +0,0 @@
# 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*

View File

@ -1,46 +0,0 @@
# 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/).

File diff suppressed because it is too large Load Diff

View File

@ -1,55 +0,0 @@
{
"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

@ -1,47 +0,0 @@
<!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

@ -1,15 +0,0 @@
{
"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

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

View File

@ -1,115 +0,0 @@
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";
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;
}, [config?.preview_title]);
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

@ -1,53 +0,0 @@
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

@ -1,65 +0,0 @@
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

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

View File

@ -1,53 +0,0 @@
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

@ -1,26 +0,0 @@
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

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

View File

@ -1,18 +0,0 @@
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

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

View File

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

View File

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

View File

@ -1,19 +0,0 @@
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;
}
const CONFIG_STORAGE_KEY = "CONFIG_STORAGE_KEY";
export const useConfig = (defaultConfig?: Config) => {
const [config] = useLocalStorage(CONFIG_STORAGE_KEY, defaultConfig);
return config;
};

View File

@ -1,34 +0,0 @@
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

@ -1,33 +0,0 @@
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);

View File

@ -1,20 +0,0 @@
import React from "react";
import ReactDOM from "react-dom/client";
import "./output.css";
import "highlight.js/styles/atom-one-dark.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();

View File

@ -1,106 +0,0 @@
@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);
}
}

View File

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

View File

@ -1,15 +0,0 @@
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

@ -1,5 +0,0 @@
// 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

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

View File

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

View File

@ -1,20 +0,0 @@
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;

View File

@ -1,26 +0,0 @@
{
"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

File diff suppressed because it is too large Load Diff

View File

@ -1,18 +0,0 @@
[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"

View File

@ -1,15 +0,0 @@
{
"files": {
"main.css": "/static/css/main.6effe17c.css",
"main.js": "/static/js/main.ba6df6e2.js",
"static/js/592.7f72a991.chunk.js": "/static/js/592.7f72a991.chunk.js",
"index.html": "/index.html",
"main.6effe17c.css.map": "/static/css/main.6effe17c.css.map",
"main.ba6df6e2.js.map": "/static/js/main.ba6df6e2.js.map",
"592.7f72a991.chunk.js.map": "/static/js/592.7f72a991.chunk.js.map"
},
"entrypoints": [
"static/css/main.6effe17c.css",
"static/js/main.ba6df6e2.js"
]
}

View File

@ -1,15 +0,0 @@
{
"files": {
"main.css": "/static/css/main.85ea3771.css",
"main.js": "/static/js/main.1bfab77c.js",
"static/js/592.7f72a991.chunk.js": "/static/js/592.7f72a991.chunk.js",
"index.html": "/index.html",
"main.85ea3771.css.map": "/static/css/main.85ea3771.css.map",
"main.1bfab77c.js.map": "/static/js/main.1bfab77c.js.map",
"592.7f72a991.chunk.js.map": "/static/js/592.7f72a991.chunk.js.map"
},
"entrypoints": [
"static/css/main.85ea3771.css",
"static/js/main.1bfab77c.js"
]
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.8 KiB

View File

@ -1 +0,0 @@
<!doctype html><html lang="en"><head><meta charset="utf-8"/><link rel="icon" href="/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="/logo192.png"/><link rel="manifest" href="/manifest.json"/><title>React App</title><script defer="defer" src="/static/js/main.1bfab77c.js"></script><link href="/static/css/main.85ea3771.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div></body></html>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.4 KiB

View File

@ -1,15 +0,0 @@
{
"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

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

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1,2 +0,0 @@
"use strict";(self.webpackChunkmy_app=self.webpackChunkmy_app||[]).push([[592],{592:(e,t,n)=>{n.r(t),n.d(t,{getCLS:()=>y,getFCP:()=>g,getFID:()=>C,getLCP:()=>P,getTTFB:()=>D});var i,r,a,o,u=function(e,t){return{name:e,value:void 0===t?-1:t,delta:0,entries:[],id:"v2-".concat(Date.now(),"-").concat(Math.floor(8999999999999*Math.random())+1e12)}},c=function(e,t){try{if(PerformanceObserver.supportedEntryTypes.includes(e)){if("first-input"===e&&!("PerformanceEventTiming"in self))return;var n=new PerformanceObserver((function(e){return e.getEntries().map(t)}));return n.observe({type:e,buffered:!0}),n}}catch(e){}},f=function(e,t){var n=function n(i){"pagehide"!==i.type&&"hidden"!==document.visibilityState||(e(i),t&&(removeEventListener("visibilitychange",n,!0),removeEventListener("pagehide",n,!0)))};addEventListener("visibilitychange",n,!0),addEventListener("pagehide",n,!0)},s=function(e){addEventListener("pageshow",(function(t){t.persisted&&e(t)}),!0)},m=function(e,t,n){var i;return function(r){t.value>=0&&(r||n)&&(t.delta=t.value-(i||0),(t.delta||void 0===i)&&(i=t.value,e(t)))}},v=-1,p=function(){return"hidden"===document.visibilityState?0:1/0},d=function(){f((function(e){var t=e.timeStamp;v=t}),!0)},l=function(){return v<0&&(v=p(),d(),s((function(){setTimeout((function(){v=p(),d()}),0)}))),{get firstHiddenTime(){return v}}},g=function(e,t){var n,i=l(),r=u("FCP"),a=function(e){"first-contentful-paint"===e.name&&(f&&f.disconnect(),e.startTime<i.firstHiddenTime&&(r.value=e.startTime,r.entries.push(e),n(!0)))},o=window.performance&&performance.getEntriesByName&&performance.getEntriesByName("first-contentful-paint")[0],f=o?null:c("paint",a);(o||f)&&(n=m(e,r,t),o&&a(o),s((function(i){r=u("FCP"),n=m(e,r,t),requestAnimationFrame((function(){requestAnimationFrame((function(){r.value=performance.now()-i.timeStamp,n(!0)}))}))})))},h=!1,T=-1,y=function(e,t){h||(g((function(e){T=e.value})),h=!0);var n,i=function(t){T>-1&&e(t)},r=u("CLS",0),a=0,o=[],v=function(e){if(!e.hadRecentInput){var t=o[0],i=o[o.length-1];a&&e.startTime-i.startTime<1e3&&e.startTime-t.startTime<5e3?(a+=e.value,o.push(e)):(a=e.value,o=[e]),a>r.value&&(r.value=a,r.entries=o,n())}},p=c("layout-shift",v);p&&(n=m(i,r,t),f((function(){p.takeRecords().map(v),n(!0)})),s((function(){a=0,T=-1,r=u("CLS",0),n=m(i,r,t)})))},E={passive:!0,capture:!0},w=new Date,L=function(e,t){i||(i=t,r=e,a=new Date,F(removeEventListener),S())},S=function(){if(r>=0&&r<a-w){var e={entryType:"first-input",name:i.type,target:i.target,cancelable:i.cancelable,startTime:i.timeStamp,processingStart:i.timeStamp+r};o.forEach((function(t){t(e)})),o=[]}},b=function(e){if(e.cancelable){var t=(e.timeStamp>1e12?new Date:performance.now())-e.timeStamp;"pointerdown"==e.type?function(e,t){var n=function(){L(e,t),r()},i=function(){r()},r=function(){removeEventListener("pointerup",n,E),removeEventListener("pointercancel",i,E)};addEventListener("pointerup",n,E),addEventListener("pointercancel",i,E)}(t,e):L(t,e)}},F=function(e){["mousedown","keydown","touchstart","pointerdown"].forEach((function(t){return e(t,b,E)}))},C=function(e,t){var n,a=l(),v=u("FID"),p=function(e){e.startTime<a.firstHiddenTime&&(v.value=e.processingStart-e.startTime,v.entries.push(e),n(!0))},d=c("first-input",p);n=m(e,v,t),d&&f((function(){d.takeRecords().map(p),d.disconnect()}),!0),d&&s((function(){var a;v=u("FID"),n=m(e,v,t),o=[],r=-1,i=null,F(addEventListener),a=p,o.push(a),S()}))},k={},P=function(e,t){var n,i=l(),r=u("LCP"),a=function(e){var t=e.startTime;t<i.firstHiddenTime&&(r.value=t,r.entries.push(e),n())},o=c("largest-contentful-paint",a);if(o){n=m(e,r,t);var v=function(){k[r.id]||(o.takeRecords().map(a),o.disconnect(),k[r.id]=!0,n(!0))};["keydown","click"].forEach((function(e){addEventListener(e,v,{once:!0,capture:!0})})),f(v,!0),s((function(i){r=u("LCP"),n=m(e,r,t),requestAnimationFrame((function(){requestAnimationFrame((function(){r.value=performance.now()-i.timeStamp,k[r.id]=!0,n(!0)}))}))}))}},D=function(e){var t,n=u("TTFB");t=function(){try{var t=performance.getEntriesByType("navigation")[0]||function(){var e=performance.timing,t={entryType:"navigation",startTime:0};for(var n in e)"navigationStart"!==n&&"toJSON"!==n&&(t[n]=Math.max(e[n]-e.navigationStart,0));return t}();if(n.value=n.delta=t.responseStart,n.value<0||n.value>performance.now())return;n.entries=[t],e(n)}catch(e){}},"complete"===document.readyState?setTimeout(t,0):addEventListener("load",(function(){return setTimeout(t,0)}))}}}]);
//# sourceMappingURL=592.7f72a991.chunk.js.map

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1,39 +0,0 @@
/**
* @license React
* react-dom.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* @license React
* react-jsx-runtime.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* @license React
* react.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* @license React
* scheduler.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1,39 +0,0 @@
/**
* @license React
* react-dom.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* @license React
* react-jsx-runtime.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* @license React
* react.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* @license React
* scheduler.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

File diff suppressed because one or more lines are too long

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