Added vscode settings

This commit is contained in:
Kristofers Solo
2022-04-28 20:54:44 +03:00
parent 245c3ca779
commit 837a479d82
25004 changed files with 2499800 additions and 0 deletions

View File

@@ -0,0 +1,3 @@
out/**
assets/**
.vscode*/**

View File

@@ -0,0 +1 @@
out/

View File

@@ -0,0 +1,81 @@
version: 2
updates:
- package-ecosystem: npm
directory: "/"
schedule:
interval: daily
time: "04:00"
open-pull-requests-limit: 10
ignore:
- dependency-name: "@types/node"
versions:
- 14.14.22
- 14.14.24
- 14.14.25
- 14.14.26
- 14.14.28
- 14.14.30
- 14.14.31
- 14.14.32
- 14.14.33
- 14.14.34
- 14.14.35
- 14.14.36
- 14.14.37
- 14.14.39
- 14.14.41
- 15.0.0
- dependency-name: eslint
versions:
- 7.18.0
- 7.19.0
- 7.20.0
- 7.22.0
- 7.23.0
- 7.24.0
- dependency-name: "@typescript-eslint/parser"
versions:
- 4.14.1
- 4.14.2
- 4.15.0
- 4.15.1
- 4.15.2
- 4.16.1
- 4.18.0
- 4.19.0
- 4.20.0
- 4.21.0
- dependency-name: "@typescript-eslint/eslint-plugin"
versions:
- 4.14.1
- 4.14.2
- 4.15.0
- 4.15.1
- 4.15.2
- 4.16.1
- 4.18.0
- 4.19.0
- 4.20.0
- 4.21.0
- dependency-name: "@types/mocha"
versions:
- 8.2.1
- dependency-name: typescript
versions:
- 4.1.4
- 4.1.5
- 4.2.2
- 4.2.3
- dependency-name: chai
versions:
- 4.3.0
- 4.3.1
- dependency-name: mocha
versions:
- 8.3.0
- dependency-name: "@types/vscode"
versions:
- 1.53.0
- dependency-name: vscode-test
versions:
- 1.5.0

View File

@@ -0,0 +1,31 @@
# This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions
name: Node.js CI
on:
push:
branches: [ main ]
pull_request: {}
jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
matrix:
node-version: [10.x, 12.x, 14.x]
os: [macos-latest, ubuntu-latest]
steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- run: npm ci
- run: xvfb-run -a npm test
if: runner.os == 'Linux'
- run: npm test
if: runner.os != 'Linux'

View File

@@ -0,0 +1,18 @@
name: Open vsx publish
on:
release:
types: [created]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
# Setup .npmrc file to publish to npm
- uses: actions/setup-node@v2
with:
node-version: '12.x'
registry-url: 'https://registry.npmjs.org'
- run: npm install
- run: npx ovsx publish -p $TOKEN
env:
TOKEN: ${{ secrets.VSXTOKEN }}

View File

@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="utf-8"?>
<PackageManifest Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011" xmlns:d="http://schemas.microsoft.com/developer/vsx-schema-design/2011">
<Metadata>
<Identity Language="en-US" Id="vscode-colorize" Version="0.11.1" Publisher="kamikillerto"/>
<DisplayName>colorize</DisplayName>
<Description xml:space="preserve">A vscode extension to help visualize css colors in files.</Description>
<Tags>color,css,hexa,hsl,rgb,preprocessor</Tags>
<Categories>Other</Categories>
<GalleryFlags>Public</GalleryFlags>
<Badges></Badges>
<Properties>
<Property Id="Microsoft.VisualStudio.Code.Engine" Value="^1.54.0" />
<Property Id="Microsoft.VisualStudio.Code.ExtensionDependencies" Value="" />
<Property Id="Microsoft.VisualStudio.Code.ExtensionPack" Value="" />
<Property Id="Microsoft.VisualStudio.Code.ExtensionKind" Value="workspace" />
<Property Id="Microsoft.VisualStudio.Code.LocalizedLanguages" Value="" />
<Property Id="Microsoft.VisualStudio.Services.Links.Source" Value="https://github.com/kamikillerto/vscode-colorize.git" />
<Property Id="Microsoft.VisualStudio.Services.Links.Getstarted" Value="https://github.com/kamikillerto/vscode-colorize.git" />
<Property Id="Microsoft.VisualStudio.Services.Links.GitHub" Value="https://github.com/kamikillerto/vscode-colorize.git" />
<Property Id="Microsoft.VisualStudio.Services.Links.Support" Value="https://github.com/kamikillerto/vscode-colorize/issues" />
<Property Id="Microsoft.VisualStudio.Services.Links.Learn" Value="https://github.com/kamikillerto/vscode-colorize/blob/master/README.MD" />
<Property Id="Microsoft.VisualStudio.Services.Branding.Theme" Value="light" />
<Property Id="Microsoft.VisualStudio.Services.GitHubFlavoredMarkdown" Value="true" />
</Properties>
<License>extension/LICENSE.txt</License>
<Icon>extension/assets/logo.png</Icon>
</Metadata>
<Installation>
<InstallationTarget Id="Microsoft.VisualStudio.Code"/>
</Installation>
<Dependencies/>
<Assets>
<Asset Type="Microsoft.VisualStudio.Code.Manifest" Path="extension/package.json" Addressable="true" />
<Asset Type="Microsoft.VisualStudio.Services.Content.Details" Path="extension/README.md" Addressable="true" /><Asset Type="Microsoft.VisualStudio.Services.Content.Changelog" Path="extension/CHANGELOG.md" Addressable="true" /><Asset Type="Microsoft.VisualStudio.Services.Content.License" Path="extension/LICENSE.txt" Addressable="true" /><Asset Type="Microsoft.VisualStudio.Services.Icons.Default" Path="extension/assets/logo.png" Addressable="true" />
</Assets>
</PackageManifest>

View File

@@ -0,0 +1,336 @@
# Changelog
## 0.11.1
### Fix
Extract browser colors surrounded by quotes.
## 0.11.0
### Features
#### Use color's alpha value to generate background
Now colorize render backgrounds with alpha value 🎉.
## 0.10.0
### Features
#### Colorize status in status bar
Now, there's an item in the status bar indicating if colorize is activated for the current file or not.
![Status bar item when colorize is activated](https://raw.githubusercontent.com/kamikillerto/vscode-colorize/master/assets/colorize-activated.png)
![Status bar item when colorize is not activated](https://raw.githubusercontent.com/kamikillerto/vscode-colorize/master/assets/colorize-not-activated.png)
#### New decoration type
It's now possible to render colors as a line below the color.
To change the way colors are displayed, change the value of the setting `colorize.decoration_type`.
This setting accepts the two values `background` and `underline`:
- `background`, colors are rendered as a background for the text.
![color displayed as background](https://raw.githubusercontent.com/kamikillerto/vscode-colorize/master/assets/decoration-background.png)
- `underline`, colors are displayed as a line below the text.
![color displayed as underline](https://raw.githubusercontent.com/kamikillerto/vscode-colorize/master/assets/decoration-underline.png)
## 0.9.2
### Fix
Check an issue preventing the extension form working with the Tabnine extension.
## 0.9.1
### Fix
Add default values for setting `colorize.include` to ensure CSS, SASS and LESS variables are extracted by default on windows10. For some reason, For some reason, vscode does not behave the same on windows 10 as on Linux/macOS. As a result, the extension cannot auto-extract variables from css/scss/sass files using only the list of languages listed on the `colorize.languages` setting.
## 0.9.0
### Breaking
#### Remove deprecated setting `colorize.files_extension`
Now the extension will only use the values of the settings `colorize.languages`, `colorize.include` and `colorize.exclude` to decide whether or colors should be decorated in a file.
#### Make `colorize.colorize_only_visible_beta` the default behavior
The purpose of this option was to only generate a colored background for colors that are on the visible part of the editor. This has a huge perf impact especially for big files with a lot of colors.
The setting `colorize.colorize_only_visible_beta` was introduced a long time ago without any issues. So it's now the default behavior.
### Fix
Correct a typo preventing the browser color `burlywood` from being colorized.
### BUILD
Update extension to latest target latest version of vscode.
## 0.8.16
- [IMPROVE] Better argb colors support
## 0.8.15
- [FIX] Exclude terminal from the list of text editors.
## 0.8.14
- [IMPROVE] Colorize argb colors with 0x prefix
## 0.8.13
- [FIX] [#291](https://github.com/kamikillerto/vscode-colorize/issues/291) Remove Alpha value in ARGB only if alpha is defined
## 0.8.11
- [FIX] [#264](https://github.com/kamikillerto/vscode-colorize/issues/264) Colorize hexa colors starting with `0x`
## 0.8.10
- [FEATURE] [#226](https://github.com/kamikillerto/vscode-colorize/issues/226) Add colorization for ARGB colors
## 0.8.9
- [FIX] Some bugfixes and crashfixes for `colorize_only_visible_beta`
## 0.8.8
- [FIX] Some bugfixes for `colorize_only_visible_beta`
## 0.8.7
- [FIX] Don't try to colorize one more line than the visible range when it's the end of the file
- [CHANGE] Remove the wait time before generating decorations on scroll
## 0.8.6
- [FEATURE] Add a new feature to colorize/update only the visible text. The feature is in beta and activable using the new setting `colorize_only_visible_beta`.
- [FIX] Remove the warning message about variables search as it's not a problem anymore.
- [FIX] Set property `rangeBehavior` to `ClosedClosed` to make sure a decoration never expand
## 0.8.5
- [FIX] No more ram pick at boot time
- [FIX] Stylus variables with underscore are now detected
## 0.8.4
- [FIX] Remove a blinking effect when updating the content of a variable.
## 0.8.3
- [CHANGE] Enable the search variables at boot time again, but explain why vscode might feel slow at opening time.
## 0.8.2
- [CHANGE] Disable search variables at boot time
- [FEATURE] Add a setting to enable/disable variables search at boot time
## 0.8.1
- [FIX] Fix an issue where alpha values with multiples `0` were not correctly colorized (like 0.00 or 1.00).
## 0.8.0
- [FEATURE] Add two new settings `colorize.include` and `colorize.exclude`. These two settings can be used to add/remove files to the list of files that can be colorized.
- [DEPRECATE] With the release of `colorize.include` and `colorize.exclude`, the setting `colorize.files_extensions` is now deprecated.
- [IMPROVEMENT] Now the list of files/folder that can be colorized or used for the variables search is determined using the three settings `colorize.include`, `colorize.exclude` and `colorize.languages`. It was static previously.
- [FIX] `}` is now a valid end for a color.
## 0.7.2
- [CHANGE] Now rgb(a) and hsl(a) colors can have decimal values
## 0.7.1
- [FIX] Fix stylus variables decoration
## 0.7.0
- [IMPROVE] Variables support fully working
- [ADDED] Options to enable/disabled colorization for colors/variables type
## 0.6.21
- [FIX] Fix css variables decoration
## 0.6.20
- [FIX] Fix perfs issue with stylus variables extraction
## 0.6.19
- [IMPROVE] Settings HOT Reload.
- [IMPROVE] Variables usage live update
## 0.6.18
- [FIX] Sass variables extraction
## 0.6.17
- [FIX] Colorize uppercased browsers colors (red, blue...)
- [IMPROVE] Colorize hexa colors with 0x prefix
- [IMPROVE] Update variables extractions. Split the variable extractions in specialized strategies (one for sass, css, less ...).
## 0.6.16
- [FIX] Split the regexp extracting variables in three to prevent a crash (the previous one was too complex).
## 0.6.15
- [FIX] Remove trailing `const` preventing variables to be decorated.
## 0.6.14
- [IMPROVE] Reduce the number of promises created during colors/variables extractions. Now the extraction of colors and variables is more than 10 times faster.
## 0.6.13
- Improve decorations contrast for variables too
## 0.6.12
- [FIX] [#106](https://github.com/kamikillerto/vscode-colorize/issues/106) - Decorations were not disable for a line accessed from a deletion. Also hide decorations on default selected line on file opening.
- [FIX] [#112](https://github.com/kamikillerto/vscode-colorize/issues/112) - Improve decorations contrast (between background and text) by following the WCAG guidelines ([Contrast (Enhanced)](https://www.w3.org/WAI/WCAG20/quickref/#qr-visual-audio-contrast7) and [Contrast (Minimum)](https://www.w3.org/WAI/WCAG20/quickref/#visual-audio-contrast-contrast))
- [FIX] [#113](https://github.com/kamikillerto/vscode-colorize/issues/113) - SASS and LESS variables like `$var_1A`, $var_A` and `$var-1` were extracted but not colorized.
## 0.6.11
- [FIX] [#97](https://github.com/kamikillerto/vscode-colorize/issues/97) - find closest declarations on windows not working due to trailing `\`
- [FIX] Variables ending with ';' not extracted
- [IMPROVE] Add more error handling to prevent colorize crash
## 0.6.10
- [IMPROVE] Wait for the end of the variables extraction before settings files/editor changes listener. Previous behavior were causing multiple useless call to the CacheManager
- Continue code splitting.
## 0.6.9
- [CHANGE] Now variables decorations are generated using the closest declaration
## 0.6.8
- [FIX] [#76](https://github.com/kamikillerto/vscode-colorize/issues/76) - Now spaces between variables names and declarations delimiters are accepted. It means this `$myVar : #ffffff` is a valid variable declaration
- [ADDED] Multi-lignes cursor support to "Hide current line decorations"
## 0.6.7
- [FIX] Line deletion truncate all stored variables
- [FIX] Deleting a variable will now delete her decorations
- [FIX] Updating a variable with an invalid color will now delete her decorations
## 0.6.6
- [FIX] Variables created from another variables not colorized
## 0.6.5
- [CHANGE] Now variables created from an other variables are colorized
- [CHANGE] Add a new gif to show variables support
- [FIX] Do not extract variables without color (like size variables)
## 0.6.4
- [FIX] [#62](https://github.com/kamikillerto/vscode-colorize/issues/62) variables not deleted
- [FIX] stylus variables not colorized
- [FIX] multiple deco for one variables use positions of the last one
- [CHANGE] Split code between color and variables (not same needs)
## 0.6.3
- [FIX] [#62](https://github.com/kamikillerto/vscode-colorize/issues/62) variables not deleted
## 0.6.2
- [FIX] [#61](https://github.com/kamikillerto/vscode-colorize/issues/61) New variables not colorized
- [CHANGE] Use await/async to improve code readability
## 0.6.1
- [FIX] Add missing error callback to openTextDocument (variables beta). Fix errors with binary type documents
## 0.6.0
- [ADD] Decorations toggle. Decorations on the current line are now hidden by default.
- [ADD] New a option (setting) `hide_current_line_decorations` to activate/deactivate the decoration toggle feature.
- [ADD] Variables (css, less, sass...) support under beta. The `activate_variables_support_beta` setting should be set to true in order to activate the feature.
## 0.5.1
- [FIX] fix a typo error that prevent postcss files to be colorized by default
## 0.5.0
- [ADD] Add hsl(a) color extraction
- [FIX] [#35](https://github.com/kamikillerto/vscode-colorize/issues/35) Should prevent no longer have side effects on other extensions
## 0.4.2
- [FIX] [#28](https://github.com/kamikillerto/vscode-colorize/issues/28), now `.x` is a valid alpha value
- [CHANGE] Add `\r` as a valid end for a color
- [CHANGE] Save files decorations in two map one for dirty files and one for saved files, fix issues with opening/reopening files
## 0.4.1
- [FIX] [#26](https://github.com/kamikillerto/vscode-colorize/issues/26) Do not colorize browsers colors inside a word
- [CHANGE] Remove the use of `Promise` in `queue.ts` to fix an error of background generation/update caused by a 1s timeout
## 0.4.0
- [REFACTO] Colors extractions
- [FIX] [#20](https://github.com/kamikillerto/vscode-colorize/issues/20) Support for split view
- [FIX] [#11](https://github.com/kamikillerto/vscode-colorize/issues/11) Colorize all colors in gradient statement
- [ADD] Cross browser colors extraction (#12)
- [FIX] [#13](https://github.com/kamikillerto/vscode-colorize/issues/13) Add a settings options to easily add new languages support
## 0.3.2
- [ADD] Stylus and XML support
- [FIX] Catch line does not exist error, avoid extension crash when all lines are removed
- [FIX] Improve deco map update on content added or removed, this should solve all sync issues
## 0.3.1
- [FIX] Use the capture group for rgb(a) the decoration and not the complete match
- [FIX] Generate decorations only once, after the end of the text analysis
## 0.3.0
### Added
- [ADD] New regex for rgb(a) colors detection
- [ADD] New activationEvents (pcss and sss)
- [ADD] rgb(a) color extraction
- [ADD] rgb and luminance properties in color.ts
- [REFACTO] Use Promise for background generation/update for easy chaining
## 0.2.0
- [ADD] `lib/Queue.ts` for queuing task. Ensure that a document update cannot cause side effect to another one.
- [FIX] Colored background update
## 0.1.2
- [FIX] Colored background update
## 0.1.1
- [CHANGE] Logo less pixelated
- [CHANGE] README
## 0.1.0 2017.01.17
- [ADD] Regex matching css hexa colors
- [ADD] Colored background generation
- [ADD] Colored background update

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 MiB

View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,121 @@
# __Colorize__ [Looking for maintainers]
[![codebeat badge](https://codebeat.co/badges/aec222e1-64ae-4360-a849-d077040694ca)](https://codebeat.co/projects/github-com-kamikillerto-vscode-colorize)
[![Build Status](https://travis-ci.org/KamiKillertO/vscode-colorize.svg?branch=master)](https://travis-ci.org/KamiKillertO/vscode-colorize)
[![Build status](https://ci.appveyor.com/api/projects/status/db69dsx996bdnj4p/branch/develop?svg=true)](https://ci.appveyor.com/project/KamiKillertO/vscode-colorize/branch/develop)
[![Licence](https://img.shields.io/github/license/KamiKillertO/vscode_colorize.svg)](https://github.com/KamiKillertO/vscode_colorize)
![Version](https://vsmarketplacebadge.apphb.com/version-short/kamikillerto.vscode-colorize.svg)
[![License](https://img.shields.io/badge/license-MIT-green.svg?style=flat)](https://raw.githubusercontent.com/kamikillerto/vscode-colorize/master/LICENSE)
[![Installs](https://vsmarketplacebadge.apphb.com/installs/KamiKillertO.vscode-colorize.svg)](https://marketplace.visualstudio.com/items?itemName=kamikillerto.vscode-colorize)
[![Ratings](https://vsmarketplacebadge.apphb.com/rating/kamikillerto.vscode-colorize.svg)](https://marketplace.visualstudio.com/items?itemName=kamikillerto.vscode-colorize)
Instantly visualize css colors in your css/sass/less/postcss/stylus/XML... files.
This extension your styles files looking for colors and generate a colored background (using the color) for each of them.
![](https://raw.githubusercontent.com/kamikillerto/vscode-colorize/master/assets/demo.gif)
![](https://raw.githubusercontent.com/kamikillerto/vscode-colorize/master/assets/demo_variables.gif)
💡 [How to enable variables support](#colorizecolorized_variables)
## Features
- Generate colored background for
- css variables
- preprocessor variables
- hsl/hsla colors
- cross browsers colors (_red, blue, green..._)
- css hexa color
- rgb/rgba color
- argb color
- Color background live update
## Options (settings)
The following Visual Studio Code settings are available for the Colorize extension.
These can be set in user preferences `(cmd+,)` or workspace settings `(.vscode/settings.json)`.
### colorize.languages _ARRAY_
Configure a list of languages that should be colorized. You can learn about languages at <https://code.visualstudio.com/docs/languages/overview>.
For example, if you want to colorize colors in `javascript` files, you just need to include it:
```json
"colorize.languages": [
"javascript",
// ...
]
```
### colorize.enable_search_variables _BOOLEAN_ _default: true
By default colorize read and parse all files, in your workspace, that are targeted by the settings [colorize.languages](#colorizelanguages), [colorize.include](#colorizeinclude), and [colorize.exlude](#colorizeexclude) to extract extract all variables. Thanks to this behavior all variables will have colored background even if you never open the file containing the declaration. _⚠ This setting can slown down vscode at opening_
### colorize.include
Configure glob patterns for including files and folders. By default Colorize is enable for files matching one the languages defined in the `colorize.languages` config, with this config you can enable colorize for other files or folders. Read more about glob patterns [here](https://code.visualstudio.com/docs/editor/codebasics#_advanced-search-options).
### colorize.exclude
Configure glob patterns for excluding files and folders. Colorize will not colorized colors in these files and folders and it'll also not search for variables inside. Read more about glob patterns [here](https://code.visualstudio.com/docs/editor/codebasics#_advanced-search-options).
### colorize.hide_current_line_decorations _BOOLEAN_ _default: true_
By default, decorations for the current line are hidden. Set this setting to `false` if you want to deactivate this behavior.
### colorize.colorized_colors _ARRAY_
This options allow you to enable/disable colorization for a type of colors.
Available colors are :
- `HEXA`: for hexadecimal colors: `#RGB`, `#RGBA`, `#RRGGBB`, `#RRGGBBAA`, `0xRGB`, `0xRGBA`, `0xRRGGBB` or `0xRRGGBBAA`
- `ARGB`: for argb colors: `#RGB`, `#ARGB`, `#RRGGBB` or `#AARRGGBB`
- `RGB`: for rgb colors: `rgb(r,g,b)` or `rgba(r,g,b,a)`
- `HSL`: for HSL colors: `hsl(h,s,l)` or `hsla(h,s,l,a)`
- `BROWSERS_COLORS`: for native browser's colors like `white`, `red`, `blue`...
For example, if you want to only colorize hexa colors (`#fff, #ffffff, 0xFFF`) in your files you can update the option like this :
```json
"colorize.colorized_colors": [
"HEXA"
]
```
### colorize.colorized_variables
This options allow you to enable/disable colorization for a type of variables.
For example if you use less in your project you setup the option like this
```json
"colorize.colorized_variables": [
"LESS"
]
```
_This way all @variables will be colorized_
## Roadmap
- [x] Generate background for hexa colors
- [x] Update background on color updates
- [x] Generate background for rgb colors
- [x] Generate background for rgba colors
- [x] Generate background for hsl colors
- [x] Generate background for hsla colors
- [x] Generate background for Predefined/Cross-browser colors
- [x] Generate background for preprocessor variables
- [x] Generate background for css variables
- [x] Config livereload
## Release
See [CHANGELOG](https://github.com/kamikillerto/vscode-colorize/blob/master/CHANGELOG.md) for more information.
## Contributing
Bugs, feature requests and more are welcome here [GitHub Issues](https://github.com/KamiKillertO/vscode-colorize/issues).

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 640 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<svg width="128" height="128" viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg">
<defs>
<style id="bx-google-fonts">@import url(https://fonts.googleapis.com/css?family=Roboto:100,100italic,300,300italic,400,400italic,500,500italic,700,700italic,900,900italic);</style>
</defs>
<path fill="#ff7473" d="m0 192 l512 0l0 128l-512 0z"/>
<path fill="#ffc952" d="m0 192 l460 0l-128 128l-332 0z"/>
<path fill="#47b8e0" d="m0 192 l324 0l-128 128l-196 0z"/>
<path fill="#34314c" d="m0 192 l188 0l-128 128l-60 0z"/>
<text x="58.204" y="288.844" style="fill: rgb(255, 255, 255); font-size: 96px; white-space: pre; font-family: 'Roboto';-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale;">#colorize</text>
</svg>

After

Width:  |  Height:  |  Size: 785 B

View File

@@ -0,0 +1,4 @@
language: node_js
node_js:
- 0.8
- "0.10"

View File

@@ -0,0 +1,75 @@
# Glob To Regular Expression
[![Build Status](https://travis-ci.org/fitzgen/glob-to-regexp.png?branch=master)](https://travis-ci.org/fitzgen/glob-to-regexp)
Turn a \*-wildcard style glob (`"*.min.js"`) into a regular expression
(`/^.*\.min\.js$/`)!
To match bash-like globs, eg. `?` for any single-character match, `[a-z]` for
character ranges, and `{*.html, *.js}` for multiple alternatives, call with
`{ extended: true }`.
To obey [globstars `**`](https://github.com/isaacs/node-glob#glob-primer) rules set option `{globstar: true}`.
NOTE: This changes the behavior of `*` when `globstar` is `true` as shown below:
When `{globstar: true}`: `/foo/**` will match any string that starts with `/foo/`
like `/foo/index.htm`, `/foo/bar/baz.txt`, etc. Also, `/foo/**/*.txt` will match
any string that starts with `/foo/` and ends with `.txt` like `/foo/bar.txt`,
`/foo/bar/baz.txt`, etc.
Whereas `/foo/*` (single `*`, not a globstar) will match strings that start with
`/foo/` like `/foo/index.htm`, `/foo/baz.txt` but will not match strings that
contain a `/` to the right like `/foo/bar/baz.txt`, `/foo/bar/baz/qux.dat`, etc.
Set flags on the resulting `RegExp` object by adding the `flags` property to the option object, eg `{ flags: "i" }` for ignoring case.
## Install
npm install glob-to-regexp
## Usage
```js
var globToRegExp = require('glob-to-regexp');
var re = globToRegExp("p*uck");
re.test("pot luck"); // true
re.test("pluck"); // true
re.test("puck"); // true
re = globToRegExp("*.min.js");
re.test("http://example.com/jquery.min.js"); // true
re.test("http://example.com/jquery.min.js.map"); // false
re = globToRegExp("*/www/*.js");
re.test("http://example.com/www/app.js"); // true
re.test("http://example.com/www/lib/factory-proxy-model-observer.js"); // true
// Extended globs
re = globToRegExp("*/www/{*.js,*.html}", { extended: true });
re.test("http://example.com/www/app.js"); // true
re.test("http://example.com/www/index.html"); // true
```
## License
Copyright (c) 2013, Nick Fitzgerald
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@@ -0,0 +1,130 @@
module.exports = function (glob, opts) {
if (typeof glob !== 'string') {
throw new TypeError('Expected a string');
}
var str = String(glob);
// The regexp we are building, as a string.
var reStr = "";
// Whether we are matching so called "extended" globs (like bash) and should
// support single character matching, matching ranges of characters, group
// matching, etc.
var extended = opts ? !!opts.extended : false;
// When globstar is _false_ (default), '/foo/*' is translated a regexp like
// '^\/foo\/.*$' which will match any string beginning with '/foo/'
// When globstar is _true_, '/foo/*' is translated to regexp like
// '^\/foo\/[^/]*$' which will match any string beginning with '/foo/' BUT
// which does not have a '/' to the right of it.
// E.g. with '/foo/*' these will match: '/foo/bar', '/foo/bar.txt' but
// these will not '/foo/bar/baz', '/foo/bar/baz.txt'
// Lastely, when globstar is _true_, '/foo/**' is equivelant to '/foo/*' when
// globstar is _false_
var globstar = opts ? !!opts.globstar : false;
// If we are doing extended matching, this boolean is true when we are inside
// a group (eg {*.html,*.js}), and false otherwise.
var inGroup = false;
// RegExp flags (eg "i" ) to pass in to RegExp constructor.
var flags = opts && typeof( opts.flags ) === "string" ? opts.flags : "";
var c;
for (var i = 0, len = str.length; i < len; i++) {
c = str[i];
switch (c) {
case "/":
case "$":
case "^":
case "+":
case ".":
case "(":
case ")":
case "=":
case "!":
case "|":
reStr += "\\" + c;
break;
case "?":
if (extended) {
reStr += ".";
break;
}
case "[":
case "]":
if (extended) {
reStr += c;
break;
}
case "{":
if (extended) {
inGroup = true;
reStr += "(";
break;
}
case "}":
if (extended) {
inGroup = false;
reStr += ")";
break;
}
case ",":
if (inGroup) {
reStr += "|";
break;
}
reStr += "\\" + c;
break;
case "*":
// Move over all consecutive "*"'s.
// Also store the previous and next characters
var prevChar = str[i - 1];
var starCount = 1;
while(str[i + 1] === "*") {
starCount++;
i++;
}
var nextChar = str[i + 1];
if (!globstar) {
// globstar is disabled, so treat any number of "*" as one
reStr += ".*";
} else {
// globstar is enabled, so determine if this is a globstar segment
var isGlobstar = starCount > 1 // multiple "*"'s
&& (prevChar === "/" || prevChar === undefined) // from the start of the segment
&& (nextChar === "/" || nextChar === undefined) // to the end of the segment
if (isGlobstar) {
// it's a globstar, so match zero or more path segments
reStr += "((?:[^/]*(?:\/|$))*)";
i++; // move over the "/"
} else {
// it's not a globstar, so only match one path segment
reStr += "([^/]*)";
}
}
break;
default:
reStr += c;
}
}
// When regexp 'g' flag is specified don't
// constrain the regular expression with ^ & $
if (!flags || !~flags.indexOf('g')) {
reStr = "^" + reStr + "$";
}
return new RegExp(reStr, flags);
};

View File

@@ -0,0 +1,58 @@
{
"_args": [
[
"glob-to-regexp@0.4.1",
"/home/benjaminj/Workspace/js/vscode-colorize"
]
],
"_from": "glob-to-regexp@0.4.1",
"_id": "glob-to-regexp@0.4.1",
"_inBundle": false,
"_integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==",
"_location": "/glob-to-regexp",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "glob-to-regexp@0.4.1",
"name": "glob-to-regexp",
"escapedName": "glob-to-regexp",
"rawSpec": "0.4.1",
"saveSpec": null,
"fetchSpec": "0.4.1"
},
"_requiredBy": [
"/"
],
"_resolved": "https://registry.npmjs.org/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz",
"_spec": "0.4.1",
"_where": "/home/benjaminj/Workspace/js/vscode-colorize",
"author": {
"name": "Nick Fitzgerald",
"email": "fitzgen@gmail.com"
},
"bugs": {
"url": "https://github.com/fitzgen/glob-to-regexp/issues"
},
"description": "Convert globs to regular expressions",
"homepage": "https://github.com/fitzgen/glob-to-regexp#readme",
"keywords": [
"regexp",
"glob",
"regexps",
"regular expressions",
"regular expression",
"wildcard"
],
"license": "BSD-2-Clause",
"main": "index.js",
"name": "glob-to-regexp",
"repository": {
"type": "git",
"url": "git+https://github.com/fitzgen/glob-to-regexp.git"
},
"scripts": {
"test": "node test.js"
},
"version": "0.4.1"
}

View File

@@ -0,0 +1,235 @@
var globToRegexp = require("./index.js");
var assert = require("assert");
function assertMatch(glob, str, opts) {
//console.log(glob, globToRegexp(glob, opts));
assert.ok(globToRegexp(glob, opts).test(str));
}
function assertNotMatch(glob, str, opts) {
//console.log(glob, globToRegexp(glob, opts));
assert.equal(false, globToRegexp(glob, opts).test(str));
}
function test(globstar) {
// Match everything
assertMatch("*", "foo");
assertMatch("*", "foo", { flags: 'g' });
// Match the end
assertMatch("f*", "foo");
assertMatch("f*", "foo", { flags: 'g' });
// Match the start
assertMatch("*o", "foo");
assertMatch("*o", "foo", { flags: 'g' });
// Match the middle
assertMatch("f*uck", "firetruck");
assertMatch("f*uck", "firetruck", { flags: 'g' });
// Don't match without Regexp 'g'
assertNotMatch("uc", "firetruck");
// Match anywhere with RegExp 'g'
assertMatch("uc", "firetruck", { flags: 'g' });
// Match zero characters
assertMatch("f*uck", "fuck");
assertMatch("f*uck", "fuck", { flags: 'g' });
// More complex matches
assertMatch("*.min.js", "http://example.com/jquery.min.js", {globstar: false});
assertMatch("*.min.*", "http://example.com/jquery.min.js", {globstar: false});
assertMatch("*/js/*.js", "http://example.com/js/jquery.min.js", {globstar: false});
// More complex matches with RegExp 'g' flag (complex regression)
assertMatch("*.min.*", "http://example.com/jquery.min.js", { flags: 'g' });
assertMatch("*.min.js", "http://example.com/jquery.min.js", { flags: 'g' });
assertMatch("*/js/*.js", "http://example.com/js/jquery.min.js", { flags: 'g' });
// Test string "\\\\/$^+?.()=!|{},[].*" represents <glob>\\/$^+?.()=!|{},[].*</glob>
// The equivalent regex is: /^\\\/\$\^\+\?\.\(\)\=\!\|\{\}\,\[\]\..*$/
// Both glob and regex match: \/$^+?.()=!|{},[].*
var testStr = "\\\\/$^+?.()=!|{},[].*";
var targetStr = "\\/$^+?.()=!|{},[].*";
assertMatch(testStr, targetStr);
assertMatch(testStr, targetStr, { flags: 'g' });
// Equivalent matches without/with using RegExp 'g'
assertNotMatch(".min.", "http://example.com/jquery.min.js");
assertMatch("*.min.*", "http://example.com/jquery.min.js");
assertMatch(".min.", "http://example.com/jquery.min.js", { flags: 'g' });
assertNotMatch("http:", "http://example.com/jquery.min.js");
assertMatch("http:*", "http://example.com/jquery.min.js");
assertMatch("http:", "http://example.com/jquery.min.js", { flags: 'g' });
assertNotMatch("min.js", "http://example.com/jquery.min.js");
assertMatch("*.min.js", "http://example.com/jquery.min.js");
assertMatch("min.js", "http://example.com/jquery.min.js", { flags: 'g' });
// Match anywhere (globally) using RegExp 'g'
assertMatch("min", "http://example.com/jquery.min.js", { flags: 'g' });
assertMatch("/js/", "http://example.com/js/jquery.min.js", { flags: 'g' });
assertNotMatch("/js*jq*.js", "http://example.com/js/jquery.min.js");
assertMatch("/js*jq*.js", "http://example.com/js/jquery.min.js", { flags: 'g' });
// Extended mode
// ?: Match one character, no more and no less
assertMatch("f?o", "foo", { extended: true });
assertNotMatch("f?o", "fooo", { extended: true });
assertNotMatch("f?oo", "foo", { extended: true });
// ?: Match one character with RegExp 'g'
assertMatch("f?o", "foo", { extended: true, globstar: globstar, flags: 'g' });
assertMatch("f?o", "fooo", { extended: true, globstar: globstar, flags: 'g' });
assertMatch("f?o?", "fooo", { extended: true, globstar: globstar, flags: 'g' });
assertNotMatch("?fo", "fooo", { extended: true, globstar: globstar, flags: 'g' });
assertNotMatch("f?oo", "foo", { extended: true, globstar: globstar, flags: 'g' });
assertNotMatch("foo?", "foo", { extended: true, globstar: globstar, flags: 'g' });
// []: Match a character range
assertMatch("fo[oz]", "foo", { extended: true });
assertMatch("fo[oz]", "foz", { extended: true });
assertNotMatch("fo[oz]", "fog", { extended: true });
// []: Match a character range and RegExp 'g' (regresion)
assertMatch("fo[oz]", "foo", { extended: true, globstar: globstar, flags: 'g' });
assertMatch("fo[oz]", "foz", { extended: true, globstar: globstar, flags: 'g' });
assertNotMatch("fo[oz]", "fog", { extended: true, globstar: globstar, flags: 'g' });
// {}: Match a choice of different substrings
assertMatch("foo{bar,baaz}", "foobaaz", { extended: true });
assertMatch("foo{bar,baaz}", "foobar", { extended: true });
assertNotMatch("foo{bar,baaz}", "foobuzz", { extended: true });
assertMatch("foo{bar,b*z}", "foobuzz", { extended: true });
// {}: Match a choice of different substrings and RegExp 'g' (regression)
assertMatch("foo{bar,baaz}", "foobaaz", { extended: true, globstar: globstar, flags: 'g' });
assertMatch("foo{bar,baaz}", "foobar", { extended: true, globstar: globstar, flags: 'g' });
assertNotMatch("foo{bar,baaz}", "foobuzz", { extended: true, globstar: globstar, flags: 'g' });
assertMatch("foo{bar,b*z}", "foobuzz", { extended: true, globstar: globstar, flags: 'g' });
// More complex extended matches
assertMatch("http://?o[oz].b*z.com/{*.js,*.html}",
"http://foo.baaz.com/jquery.min.js",
{ extended: true });
assertMatch("http://?o[oz].b*z.com/{*.js,*.html}",
"http://moz.buzz.com/index.html",
{ extended: true });
assertNotMatch("http://?o[oz].b*z.com/{*.js,*.html}",
"http://moz.buzz.com/index.htm",
{ extended: true });
assertNotMatch("http://?o[oz].b*z.com/{*.js,*.html}",
"http://moz.bar.com/index.html",
{ extended: true });
assertNotMatch("http://?o[oz].b*z.com/{*.js,*.html}",
"http://flozz.buzz.com/index.html",
{ extended: true });
// More complex extended matches and RegExp 'g' (regresion)
assertMatch("http://?o[oz].b*z.com/{*.js,*.html}",
"http://foo.baaz.com/jquery.min.js",
{ extended: true, globstar: globstar, flags: 'g' });
assertMatch("http://?o[oz].b*z.com/{*.js,*.html}",
"http://moz.buzz.com/index.html",
{ extended: true, globstar: globstar, flags: 'g' });
assertNotMatch("http://?o[oz].b*z.com/{*.js,*.html}",
"http://moz.buzz.com/index.htm",
{ extended: true, globstar: globstar, flags: 'g' });
assertNotMatch("http://?o[oz].b*z.com/{*.js,*.html}",
"http://moz.bar.com/index.html",
{ extended: true, globstar: globstar, flags: 'g' });
assertNotMatch("http://?o[oz].b*z.com/{*.js,*.html}",
"http://flozz.buzz.com/index.html",
{ extended: true, globstar: globstar, flags: 'g' });
// globstar
assertMatch("http://foo.com/**/{*.js,*.html}",
"http://foo.com/bar/jquery.min.js",
{ extended: true, globstar: globstar, flags: 'g' });
assertMatch("http://foo.com/**/{*.js,*.html}",
"http://foo.com/bar/baz/jquery.min.js",
{ extended: true, globstar: globstar, flags: 'g' });
assertMatch("http://foo.com/**",
"http://foo.com/bar/baz/jquery.min.js",
{ extended: true, globstar: globstar, flags: 'g' });
// Remaining special chars should still match themselves
// Test string "\\\\/$^+.()=!|,.*" represents <glob>\\/$^+.()=!|,.*</glob>
// The equivalent regex is: /^\\\/\$\^\+\.\(\)\=\!\|\,\..*$/
// Both glob and regex match: \/$^+.()=!|,.*
var testExtStr = "\\\\/$^+.()=!|,.*";
var targetExtStr = "\\/$^+.()=!|,.*";
assertMatch(testExtStr, targetExtStr, { extended: true });
assertMatch(testExtStr, targetExtStr, { extended: true, globstar: globstar, flags: 'g' });
}
// regression
// globstar false
test(false)
// globstar true
test(true);
// globstar specific tests
assertMatch("/foo/*", "/foo/bar.txt", {globstar: true });
assertMatch("/foo/**", "/foo/baz.txt", {globstar: true });
assertMatch("/foo/**", "/foo/bar/baz.txt", {globstar: true });
assertMatch("/foo/*/*.txt", "/foo/bar/baz.txt", {globstar: true });
assertMatch("/foo/**/*.txt", "/foo/bar/baz.txt", {globstar: true });
assertMatch("/foo/**/*.txt", "/foo/bar/baz/qux.txt", {globstar: true });
assertMatch("/foo/**/bar.txt", "/foo/bar.txt", {globstar: true });
assertMatch("/foo/**/**/bar.txt", "/foo/bar.txt", {globstar: true });
assertMatch("/foo/**/*/baz.txt", "/foo/bar/baz.txt", {globstar: true });
assertMatch("/foo/**/*.txt", "/foo/bar.txt", {globstar: true });
assertMatch("/foo/**/**/*.txt", "/foo/bar.txt", {globstar: true });
assertMatch("/foo/**/*/*.txt", "/foo/bar/baz.txt", {globstar: true });
assertMatch("**/*.txt", "/foo/bar/baz/qux.txt", {globstar: true });
assertMatch("**/foo.txt", "foo.txt", {globstar: true });
assertMatch("**/*.txt", "foo.txt", {globstar: true });
assertNotMatch("/foo/*", "/foo/bar/baz.txt", {globstar: true });
assertNotMatch("/foo/*.txt", "/foo/bar/baz.txt", {globstar: true });
assertNotMatch("/foo/*/*.txt", "/foo/bar/baz/qux.txt", {globstar: true });
assertNotMatch("/foo/*/bar.txt", "/foo/bar.txt", {globstar: true });
assertNotMatch("/foo/*/*/baz.txt", "/foo/bar/baz.txt", {globstar: true });
assertNotMatch("/foo/**.txt", "/foo/bar/baz/qux.txt", {globstar: true });
assertNotMatch("/foo/bar**/*.txt", "/foo/bar/baz/qux.txt", {globstar: true });
assertNotMatch("/foo/bar**", "/foo/bar/baz.txt", {globstar: true });
assertNotMatch("**/.txt", "/foo/bar/baz/qux.txt", {globstar: true });
assertNotMatch("*/*.txt", "/foo/bar/baz/qux.txt", {globstar: true });
assertNotMatch("*/*.txt", "foo.txt", {globstar: true });
assertNotMatch("http://foo.com/*",
"http://foo.com/bar/baz/jquery.min.js",
{ extended: true, globstar: true });
assertNotMatch("http://foo.com/*",
"http://foo.com/bar/baz/jquery.min.js",
{ globstar: true });
assertMatch("http://foo.com/*",
"http://foo.com/bar/baz/jquery.min.js",
{ globstar: false });
assertMatch("http://foo.com/**",
"http://foo.com/bar/baz/jquery.min.js",
{ globstar: true });
assertMatch("http://foo.com/*/*/jquery.min.js",
"http://foo.com/bar/baz/jquery.min.js",
{ globstar: true });
assertMatch("http://foo.com/**/jquery.min.js",
"http://foo.com/bar/baz/jquery.min.js",
{ globstar: true });
assertMatch("http://foo.com/*/*/jquery.min.js",
"http://foo.com/bar/baz/jquery.min.js",
{ globstar: false });
assertMatch("http://foo.com/*/jquery.min.js",
"http://foo.com/bar/baz/jquery.min.js",
{ globstar: false });
assertNotMatch("http://foo.com/*/jquery.min.js",
"http://foo.com/bar/baz/jquery.min.js",
{ globstar: true });
console.log("Ok!");

View File

@@ -0,0 +1,312 @@
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
exports.cleanDecorationList = exports.removeDuplicateDecorations = exports.generateDecorations = exports.updateContextDecorations = exports.q = exports.extension = exports.config = exports.colorize = exports.ColorizeContext = exports.canColorize = exports.deactivate = exports.activate = void 0;
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode_1 = require("vscode");
const color_util_1 = require("./lib/util/color-util");
const queue_1 = require("./lib/queue");
const variables_manager_1 = require("./lib/variables/variables-manager");
const cache_manager_1 = require("./lib/cache-manager");
const editor_manager_1 = require("./lib/editor-manager");
const globToRegexp = require("glob-to-regexp");
const colorize_config_1 = require("./lib/colorize-config");
const listeners_1 = require("./listeners");
let config = {
languages: [],
isHideCurrentLineDecorations: true,
colorizedVariables: [],
colorizedColors: [],
filesToExcludes: [],
filesToIncludes: [],
inferedFilesToInclude: [],
searchVariables: false,
decorationFn: null
};
exports.config = config;
class ColorizeContext {
constructor() {
this.editor = null;
this.nbLine = 0;
this.deco = new Map();
this.currentSelection = null;
this.statusBar = vscode_1.window.createStatusBarItem(vscode_1.StatusBarAlignment.Right);
}
updateStatusBar(activated) {
// List of icons can be found here https://code.visualstudio.com/api/references/icons-in-labels
const icon = activated
? '$(check)'
: '$(circle-slash)';
const color = activated
? undefined
: new vscode_1.ThemeColor('errorForeground');
const hoverMessage = activated
? 'Colorize is activated for this file'
: 'Colorize is not activated for this file';
this.statusBar.text = `${icon} Colorize`;
this.statusBar.color = color;
this.statusBar.tooltip = hoverMessage;
this.statusBar.show();
}
}
exports.ColorizeContext = ColorizeContext;
const q = new queue_1.default();
exports.q = q;
async function initDecorations(context) {
if (!context.editor) {
return;
}
const text = context.editor.document.getText();
const fileLines = color_util_1.default.textToFileLines(text);
const lines = context.editor.visibleRanges.reduce((acc, range) => {
return [
...acc,
...fileLines.slice(range.start.line, range.end.line + 2)
];
}, []);
// removeDuplicateDecorations(context);
await variables_manager_1.default.findVariablesDeclarations(context.editor.document.fileName, fileLines);
const variables = await variables_manager_1.default.findVariables(context.editor.document.fileName, lines);
const colors = await color_util_1.default.findColors(lines);
generateDecorations(colors, variables, context.deco);
return editor_manager_1.default.decorate(context.editor, context.deco, context.currentSelection);
}
function updateContextDecorations(decorations, context) {
const it = decorations.entries();
let tmp = it.next();
while (!tmp.done) {
const line = tmp.value[0];
if (context.deco.has(line)) {
context.deco.set(line, context.deco.get(line).concat(decorations.get(line)));
}
else {
context.deco.set(line, decorations.get(line));
}
tmp = it.next();
}
}
exports.updateContextDecorations = updateContextDecorations;
function removeDuplicateDecorations(context) {
const it = context.deco.entries();
const m = new Map();
let tmp = it.next();
while (!tmp.done) {
const line = tmp.value[0];
const decorations = tmp.value[1];
let newDecorations = [];
// TODO; use reduce?
decorations.forEach((deco) => {
deco.generateRange(line);
const exist = newDecorations.findIndex((_) => deco.currentRange.isEqual(_.currentRange));
if (exist !== -1) {
newDecorations[exist].dispose();
newDecorations = newDecorations.filter((_, i) => i !== exist);
}
newDecorations.push(deco);
});
m.set(line, newDecorations);
tmp = it.next();
}
context.deco = m;
}
exports.removeDuplicateDecorations = removeDuplicateDecorations;
function updateDecorationMap(map, line, decoration) {
if (map.has(line)) {
map.set(line, map.get(line).concat([decoration]));
}
else {
map.set(line, [decoration]);
}
}
function generateDecorations(colors, variables, decorations) {
colors.map(({ line, colors }) => colors.forEach((color) => {
const decoration = color_util_1.default.generateDecoration(color, line, config.decorationFn);
updateDecorationMap(decorations, line, decoration);
}));
variables.map(({ line, colors }) => colors.forEach((variable) => {
const decoration = variables_manager_1.default.generateDecoration(variable, line, config.decorationFn);
updateDecorationMap(decorations, line, decoration);
}));
return decorations;
}
exports.generateDecorations = generateDecorations;
/**
* Check if COLORIZE support a language
*
* @param {string} languageId A valid languageId
* @returns {boolean}
*/
function isLanguageSupported(languageId) {
return config.languages.indexOf(languageId) !== -1;
}
/**
* Check if the file is the `colorize.include` setting
*
* @param {string} fileName A valid filename (path to the file)
* @returns {boolean}
*/
function isIncludedFile(fileName) {
return config.filesToIncludes.find((globPattern) => globToRegexp(globPattern).test(fileName)) !== undefined;
}
/**
* Check if a file can be colorized by COLORIZE
*
* @param {TextDocument} document The document to test
* @returns {boolean}
*/
function canColorize(document) {
return isLanguageSupported(document.languageId) || isIncludedFile(document.fileName);
}
exports.canColorize = canColorize;
function handleTextSelectionChange(event, cb) {
if (!config.isHideCurrentLineDecorations || event.textEditor !== extension.editor) {
return cb();
}
if (extension.currentSelection.length !== 0) {
extension.currentSelection.forEach(line => {
const decorations = extension.deco.get(line);
if (decorations !== undefined) {
editor_manager_1.default.decorateOneLine(extension.editor, decorations, line);
}
});
}
extension.currentSelection = [];
event.selections.forEach((selection) => {
const decorations = extension.deco.get(selection.active.line);
if (decorations) {
decorations.forEach(_ => _.hide());
}
});
extension.currentSelection = event.selections.map((selection) => selection.active.line);
return cb();
}
function handleCloseOpen(document) {
q.push((cb) => {
if (extension.editor && extension.editor.document.fileName === document.fileName) {
cache_manager_1.default.saveDecorations(document, extension.deco);
return cb();
}
return cb();
});
}
async function colorize(editor, cb) {
extension.editor = null;
extension.deco = new Map();
if (!editor || !canColorize(editor.document)) {
extension.updateStatusBar(false);
return cb();
}
extension.updateStatusBar(true);
extension.editor = editor;
extension.currentSelection = editor.selections.map((selection) => selection.active.line);
const deco = cache_manager_1.default.getCachedDecorations(editor.document);
if (deco) {
extension.deco = deco;
extension.nbLine = editor.document.lineCount;
editor_manager_1.default.decorate(extension.editor, extension.deco, extension.currentSelection);
}
else {
extension.nbLine = editor.document.lineCount;
try {
await initDecorations(extension);
}
finally {
cache_manager_1.default.saveDecorations(extension.editor.document, extension.deco);
}
}
return cb();
}
exports.colorize = colorize;
function handleChangeActiveTextEditor(editor) {
if (extension.editor !== undefined && extension.editor !== null) {
extension.deco.forEach(decorations => decorations.forEach(deco => deco.hide()));
cache_manager_1.default.saveDecorations(extension.editor.document, extension.deco);
}
getVisibleFileEditors().filter(e => e !== editor).forEach(e => {
q.push(cb => colorize(e, cb));
});
q.push(cb => colorize(editor, cb));
}
function cleanDecorationList(context, cb) {
const it = context.deco.entries();
let tmp = it.next();
while (!tmp.done) {
const line = tmp.value[0];
const decorations = tmp.value[1];
context.deco.set(line, decorations.filter(decoration => !decoration.disposed));
tmp = it.next();
}
return cb();
}
exports.cleanDecorationList = cleanDecorationList;
function clearCache() {
extension.deco.clear();
extension.deco = new Map();
cache_manager_1.default.clearCache();
}
function handleConfigurationChanged() {
const newConfig = colorize_config_1.getColorizeConfig();
clearCache();
// delete current decorations then regenerate decorations
color_util_1.default.setupColorsExtractors(newConfig.colorizedColors);
q.push(async (cb) => {
// remove event listeners?
variables_manager_1.default.setupVariablesExtractors(newConfig.colorizedVariables);
if (newConfig.searchVariables) {
await variables_manager_1.default.getWorkspaceVariables(newConfig.filesToIncludes.concat(newConfig.inferedFilesToInclude), newConfig.filesToExcludes); // 👍
}
return cb();
});
exports.config = config = newConfig;
colorizeVisibleTextEditors();
}
function initEventListeners(context) {
vscode_1.window.onDidChangeTextEditorSelection((event) => q.push((cb) => handleTextSelectionChange(event, cb)), null, context.subscriptions);
vscode_1.workspace.onDidCloseTextDocument(handleCloseOpen, null, context.subscriptions);
vscode_1.workspace.onDidSaveTextDocument(handleCloseOpen, null, context.subscriptions);
vscode_1.window.onDidChangeActiveTextEditor(handleChangeActiveTextEditor, null, context.subscriptions);
vscode_1.workspace.onDidChangeConfiguration(handleConfigurationChanged, null, context.subscriptions); // Does not update when local config file is edited manualy ><
listeners_1.default.setupEventListeners(context);
}
function getVisibleFileEditors() {
return vscode_1.window.visibleTextEditors.filter(editor => editor.document.uri.scheme === 'file');
}
function colorizeVisibleTextEditors() {
extension.nbLine = 65;
getVisibleFileEditors().forEach(editor => {
q.push(cb => colorize(editor, cb));
});
}
let extension;
exports.extension = extension;
function activate(context) {
exports.extension = extension = new ColorizeContext();
exports.config = config = colorize_config_1.getColorizeConfig();
color_util_1.default.setupColorsExtractors(config.colorizedColors);
variables_manager_1.default.setupVariablesExtractors(config.colorizedVariables);
q.push(async (cb) => {
try {
if (config.searchVariables) {
await variables_manager_1.default.getWorkspaceVariables(config.filesToIncludes.concat(config.inferedFilesToInclude), config.filesToExcludes); // 👍
}
initEventListeners(context);
}
catch (error) {
// do something
}
return cb();
});
colorizeVisibleTextEditors();
return extension;
}
exports.activate = activate;
// this method is called when your extension is deactivated
function deactivate() {
extension.nbLine = null;
extension.editor = null;
extension.deco.clear();
extension.deco = null;
cache_manager_1.default.clearCache();
}
exports.deactivate = deactivate;
//# sourceMappingURL=extension.js.map

View File

@@ -0,0 +1,45 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class CacheManager {
constructor() {
this._dirtyCache = new Map();
this._decorationsCache = new Map();
}
/**
* Return the saved decorations for a document or return null if the file has never been opened before.
*
* @param {TextEditor} editor
* @returns {(Map<number, IDecoration[]> | null)}
*/
getCachedDecorations(document) {
if (!document.isDirty && this._decorationsCache.has(document.fileName)) {
return this._decorationsCache.get(document.fileName);
}
if (this._dirtyCache.has(document.fileName)) {
return this._dirtyCache.get(document.fileName);
}
return null;
}
/**
* Save a file decorations
*
* @param {TextDocument} document
* @param {Map<number, IDecoration[]>} deco
*/
saveDecorations(document, deco) {
document.isDirty ? this._saveDirtyDecoration(document.fileName, deco) : this._saveSavedDecorations(document.fileName, deco);
}
_saveDirtyDecoration(fileName, decorations) {
return this._dirtyCache.set(fileName, decorations);
}
_saveSavedDecorations(fileName, decorations) {
return this._decorationsCache.set(fileName, decorations);
}
clearCache() {
this._dirtyCache.clear();
this._decorationsCache.clear();
}
}
const instance = new CacheManager();
exports.default = instance;
//# sourceMappingURL=cache-manager.js.map

View File

@@ -0,0 +1,83 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateDecorationType = exports.getColorizeConfig = void 0;
const array_1 = require("./util/array");
const vscode_1 = require("vscode");
const color_util_1 = require("./util/color-util");
const backgroundImage = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAKQWlDQ1BJQ0MgUHJvZmlsZQAASA2dlndUU9kWh8+9N73QEiIgJfQaegkg0jtIFQRRiUmAUAKGhCZ2RAVGFBEpVmRUwAFHhyJjRRQLg4Ji1wnyEFDGwVFEReXdjGsJ7601896a/cdZ39nnt9fZZ+9917oAUPyCBMJ0WAGANKFYFO7rwVwSE8vE9wIYEAEOWAHA4WZmBEf4RALU/L09mZmoSMaz9u4ugGS72yy/UCZz1v9/kSI3QyQGAApF1TY8fiYX5QKUU7PFGTL/BMr0lSkyhjEyFqEJoqwi48SvbPan5iu7yZiXJuShGlnOGbw0noy7UN6aJeGjjAShXJgl4GejfAdlvVRJmgDl9yjT0/icTAAwFJlfzOcmoWyJMkUUGe6J8gIACJTEObxyDov5OWieAHimZ+SKBIlJYqYR15hp5ejIZvrxs1P5YjErlMNN4Yh4TM/0tAyOMBeAr2+WRQElWW2ZaJHtrRzt7VnW5mj5v9nfHn5T/T3IevtV8Sbsz55BjJ5Z32zsrC+9FgD2JFqbHbO+lVUAtG0GQOXhrE/vIADyBQC03pzzHoZsXpLE4gwnC4vs7GxzAZ9rLivoN/ufgm/Kv4Y595nL7vtWO6YXP4EjSRUzZUXlpqemS0TMzAwOl89k/fcQ/+PAOWnNycMsnJ/AF/GF6FVR6JQJhIlou4U8gViQLmQKhH/V4X8YNicHGX6daxRodV8AfYU5ULhJB8hvPQBDIwMkbj96An3rWxAxCsi+vGitka9zjzJ6/uf6Hwtcim7hTEEiU+b2DI9kciWiLBmj34RswQISkAd0oAo0gS4wAixgDRyAM3AD3iAAhIBIEAOWAy5IAmlABLJBPtgACkEx2AF2g2pwANSBetAEToI2cAZcBFfADXALDIBHQAqGwUswAd6BaQiC8BAVokGqkBakD5lC1hAbWgh5Q0FQOBQDxUOJkBCSQPnQJqgYKoOqoUNQPfQjdBq6CF2D+qAH0CA0Bv0BfYQRmALTYQ3YALaA2bA7HAhHwsvgRHgVnAcXwNvhSrgWPg63whfhG/AALIVfwpMIQMgIA9FGWAgb8URCkFgkAREha5EipAKpRZqQDqQbuY1IkXHkAwaHoWGYGBbGGeOHWYzhYlZh1mJKMNWYY5hWTBfmNmYQM4H5gqVi1bGmWCesP3YJNhGbjS3EVmCPYFuwl7ED2GHsOxwOx8AZ4hxwfrgYXDJuNa4Etw/XjLuA68MN4SbxeLwq3hTvgg/Bc/BifCG+Cn8cfx7fjx/GvyeQCVoEa4IPIZYgJGwkVBAaCOcI/YQRwjRRgahPdCKGEHnEXGIpsY7YQbxJHCZOkxRJhiQXUiQpmbSBVElqIl0mPSa9IZPJOmRHchhZQF5PriSfIF8lD5I/UJQoJhRPShxFQtlOOUq5QHlAeUOlUg2obtRYqpi6nVpPvUR9Sn0vR5Mzl/OX48mtk6uRa5Xrl3slT5TXl3eXXy6fJ18hf0r+pvy4AlHBQMFTgaOwVqFG4bTCPYVJRZqilWKIYppiiWKD4jXFUSW8koGStxJPqUDpsNIlpSEaQtOledK4tE20Otpl2jAdRzek+9OT6cX0H+i99AllJWVb5SjlHOUa5bPKUgbCMGD4M1IZpYyTjLuMj/M05rnP48/bNq9pXv+8KZX5Km4qfJUilWaVAZWPqkxVb9UU1Z2qbapP1DBqJmphatlq+9Uuq43Pp893ns+dXzT/5PyH6rC6iXq4+mr1w+o96pMamhq+GhkaVRqXNMY1GZpumsma5ZrnNMe0aFoLtQRa5VrntV4wlZnuzFRmJbOLOaGtru2nLdE+pN2rPa1jqLNYZ6NOs84TXZIuWzdBt1y3U3dCT0svWC9fr1HvoT5Rn62fpL9Hv1t/ysDQINpgi0GbwaihiqG/YZ5ho+FjI6qRq9Eqo1qjO8Y4Y7ZxivE+41smsImdSZJJjclNU9jU3lRgus+0zwxr5mgmNKs1u8eisNxZWaxG1qA5wzzIfKN5m/krCz2LWIudFt0WXyztLFMt6ywfWSlZBVhttOqw+sPaxJprXWN9x4Zq42Ozzqbd5rWtqS3fdr/tfTuaXbDdFrtOu8/2DvYi+yb7MQc9h3iHvQ732HR2KLuEfdUR6+jhuM7xjOMHJ3snsdNJp9+dWc4pzg3OowsMF/AX1C0YctFx4bgccpEuZC6MX3hwodRV25XjWuv6zE3Xjed2xG3E3dg92f24+ysPSw+RR4vHlKeT5xrPC16Il69XkVevt5L3Yu9q76c+Oj6JPo0+E752vqt9L/hh/QL9dvrd89fw5/rX+08EOASsCegKpARGBFYHPgsyCRIFdQTDwQHBu4IfL9JfJFzUFgJC/EN2hTwJNQxdFfpzGC4sNKwm7Hm4VXh+eHcELWJFREPEu0iPyNLIR4uNFksWd0bJR8VF1UdNRXtFl0VLl1gsWbPkRoxajCCmPRYfGxV7JHZyqffS3UuH4+ziCuPuLjNclrPs2nK15anLz66QX8FZcSoeGx8d3xD/iRPCqeVMrvRfuXflBNeTu4f7kufGK+eN8V34ZfyRBJeEsoTRRJfEXYljSa5JFUnjAk9BteB1sl/ygeSplJCUoykzqdGpzWmEtPi000IlYYqwK10zPSe9L8M0ozBDuspp1e5VE6JA0ZFMKHNZZruYjv5M9UiMJJslg1kLs2qy3mdHZZ/KUcwR5vTkmuRuyx3J88n7fjVmNXd1Z752/ob8wTXuaw6thdauXNu5Tnddwbrh9b7rj20gbUjZ8MtGy41lG99uit7UUaBRsL5gaLPv5sZCuUJR4b0tzlsObMVsFWzt3WazrWrblyJe0fViy+KK4k8l3JLr31l9V/ndzPaE7b2l9qX7d+B2CHfc3em681iZYlle2dCu4F2t5czyovK3u1fsvlZhW3FgD2mPZI+0MqiyvUqvakfVp+qk6oEaj5rmvep7t+2d2sfb17/fbX/TAY0DxQc+HhQcvH/I91BrrUFtxWHc4azDz+ui6rq/Z39ff0TtSPGRz0eFR6XHwo911TvU1zeoN5Q2wo2SxrHjccdv/eD1Q3sTq+lQM6O5+AQ4ITnx4sf4H++eDDzZeYp9qukn/Z/2ttBailqh1tzWibakNml7THvf6YDTnR3OHS0/m/989Iz2mZqzymdLz5HOFZybOZ93fvJCxoXxi4kXhzpXdD66tOTSna6wrt7LgZevXvG5cqnbvfv8VZerZ645XTt9nX297Yb9jdYeu56WX+x+aem172296XCz/ZbjrY6+BX3n+l37L972un3ljv+dGwOLBvruLr57/17cPel93v3RB6kPXj/Mejj9aP1j7OOiJwpPKp6qP6391fjXZqm99Oyg12DPs4hnj4a4Qy//lfmvT8MFz6nPK0a0RupHrUfPjPmM3Xqx9MXwy4yX0+OFvyn+tveV0auffnf7vWdiycTwa9HrmT9K3qi+OfrW9m3nZOjk03dp76anit6rvj/2gf2h+2P0x5Hp7E/4T5WfjT93fAn88ngmbWbm3/eE8/syOll+AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAM0lEQVQ4EWPMysr6z4AHiImJ4ZFlYGDCK0uE5KgBgyEQWQjF86tXr/BG5mg0DoZopDgWABkEBaGe4IM3AAAAAElFTkSuQmCC';
function getColorizeConfig() {
var _a;
const configuration = vscode_1.workspace.getConfiguration('colorize', (_a = vscode_1.window.activeTextEditor) === null || _a === void 0 ? void 0 : _a.document);
// remove duplicates (if duplicates)
const colorizedVariables = Array.from(new Set(configuration.get('colorized_variables', []))); // [...new Set(array)] // works too
const colorizedColors = Array.from(new Set(configuration.get('colorized_colors', []))); // [...new Set(array)] // works too
const languages = configuration.get('languages', []);
const inferedFilesToInclude = inferFilesToInclude(languages).map(extension => `**/*${extension}`);
const filesToIncludes = Array.from(new Set(configuration.get('include', [])));
const filesToExcludes = Array.from(new Set(configuration.get('exclude', [])));
const searchVariables = configuration.get('enable_search_variables', false);
return {
languages,
isHideCurrentLineDecorations: configuration.get('hide_current_line_decorations'),
colorizedColors,
colorizedVariables,
filesToIncludes,
filesToExcludes,
inferedFilesToInclude,
searchVariables,
decorationFn: generateDecorationType(configuration.get('decoration_type'))
};
}
exports.getColorizeConfig = getColorizeConfig;
function generateDecorationType(decorationType = 'background') {
switch (decorationType) {
case 'underline':
return function (color) {
return vscode_1.window.createTextEditorDecorationType({
borderWidth: '0 0 2px 0',
borderStyle: 'solid',
borderColor: color.toRgbString(),
rangeBehavior: vscode_1.DecorationRangeBehavior.ClosedClosed
});
};
case 'background':
default:
return function (color) {
const rgbaString = color.toRgbaString();
return vscode_1.window.createTextEditorDecorationType({
borderWidth: '1px',
borderStyle: 'solid',
borderColor: rgbaString,
backgroundColor: `transparent;
background-image:
linear-gradient(${rgbaString}, ${rgbaString}),
linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0) 100%),
url(${backgroundImage});
background-size: 10px 10px;
background-position: 0 0, 5px 5px;
`,
color: color_util_1.generateOptimalTextColor(color),
rangeBehavior: vscode_1.DecorationRangeBehavior.ClosedClosed
});
};
}
}
exports.generateDecorationType = generateDecorationType;
function inferFilesToInclude(languagesConfig) {
const filesExtensions = vscode_1.extensions.all.reduce((acc, extension) => {
var _a, _b;
if ((_b = (_a = extension.packageJSON) === null || _a === void 0 ? void 0 : _a.contributes) === null || _b === void 0 ? void 0 : _b.languages) {
extension.packageJSON.contributes.languages.forEach(language => {
if (languagesConfig.indexOf(language.id) !== -1 && language.extensions) {
acc = [
...acc,
...language.extensions
];
}
});
}
return acc;
}, []);
return array_1.unique(filesExtensions.flat());
}
//# sourceMappingURL=colorize-config.js.map

View File

@@ -0,0 +1,87 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const vscode_1 = require("vscode");
class ColorDecoration {
constructor(color, line, decorationFn) {
/**
* Keep track of the TextEditorDecorationType status
*
* @type {boolean}
* @public
* @memberOf ColorDecoration
*/
this.disposed = false;
this.hidden = false;
this.color = color;
this.decorationFn = decorationFn;
this.generateRange(line);
}
/**
* The TextEditorDecorationType associated to the color
*
* @type {TextEditorDecorationType}
* @memberOf ColorDecoration
*/
get decoration() {
this._generateDecorator();
return this._decoration;
}
set decoration(deco) {
this._decoration = deco;
}
get rgb() {
return this.color.rgb;
}
/**
* Dispose the TextEditorDecorationType
* (destroy the colored background)
*
* @public
* @memberOf ColorDecoration
*/
dispose() {
try {
this._decoration.dispose();
this.disposed = true;
}
catch (error) {
// do something
}
}
/**
* Hide the TextEditorDecorationType.
*
* @public
* @memberOf ColorDecoration
*/
hide() {
if (this._decoration) {
this._decoration.dispose();
}
this.hidden = true;
}
/**
* Generate the decoration Range (start and end position in line)
*
* @param {number} line
* @returns {Range}
*
* @memberOf ColorDecoration
*/
generateRange(line) {
const range = new vscode_1.Range(new vscode_1.Position(line, this.color.positionInText), new vscode_1.Position(line, this.color.positionInText + this.color.value.length));
this.currentRange = range;
return range;
}
shouldGenerateDecoration() {
if (this.disposed === true /* || this.hidden === true */) {
return false;
}
return this._decoration === null || this._decoration === undefined || this.hidden;
}
_generateDecorator() {
this._decoration = this.decorationFn(this.color);
}
}
exports.default = ColorDecoration;
//# sourceMappingURL=color-decoration.js.map

View File

@@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const color_util_1 = require("../util/color-util");
const extractor_mixin_1 = require("../extractor-mixin");
class ColorExtractor extends extractor_mixin_1.Extractor {
async extract(fileLines) {
const colors = await Promise.all(this.enabledStrategies.map(strategy => strategy.extractColors(fileLines)));
return color_util_1.flattenLineExtractionsFlatten(colors); // should regroup per lines?
}
extractOneColor(text) {
const colors = this.enabledStrategies.map(strategy => strategy.extractColor(text));
return colors.find(color => color !== null);
}
}
const instance = new ColorExtractor();
exports.default = instance;
//# sourceMappingURL=color-extractor.js.map

View File

@@ -0,0 +1,48 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class Color {
/**
* Creates an instance of Color.
*
* @param {string} value
* @param {number} [positionInText=0]
* @param {number} [alpha=1]
* @param {number[]} rgb
*
* @memberOf Color
*/
constructor(value, positionInText = 0, rgb, alpha) {
this.value = value;
this.positionInText = positionInText;
this.alpha = alpha !== null && alpha !== void 0 ? alpha : 1;
this.rgb = rgb;
}
/**
* Generate the color string rgb representation
* example :
* #fff => rgb(255, 255, 255)
* rgba(1, 34, 12, .1) => rgb(1, 34, 12)
*
* @returns {string}
* @public
* @memberOf Color
*/
toRgbString() {
return `rgb(${this.rgb.join(', ')})`;
}
/**
* Generate the color string rgb representation
* example :
* #fff => rgb(255, 255, 255)
* rgba(1, 34, 12, .1) => rgb(1, 34, 12)
*
* @returns {string}
* @public
* @memberOf Color
*/
toRgbaString() {
return `rgba(${this.rgb.join(', ')}, ${this.alpha})`;
}
}
exports.default = Color;
//# sourceMappingURL=color.js.map

View File

@@ -0,0 +1,35 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class ColorStrategy {
constructor(name, REGEXP, REGEXP_ONE, colorFromRegexp) {
this.name = name;
this.REGEXP = REGEXP;
this.REGEXP_ONE = REGEXP_ONE;
this.colorFromRegexp = colorFromRegexp;
}
async extractColors(fileLines) {
return fileLines.map(({ line, text }) => {
let match = null;
const colors = [];
while ((match = this.REGEXP.exec(text)) !== null) {
const color = this.colorFromRegexp(match);
if (color) {
colors.push(color);
}
}
return {
line,
colors
};
});
}
extractColor(text) {
const match = this.REGEXP_ONE.exec(text);
if (match) {
return this.colorFromRegexp(match);
}
return null;
}
}
exports.default = ColorStrategy;
//# sourceMappingURL=__strategy-base.js.map

View File

@@ -0,0 +1,47 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.REGEXP_ONE = exports.REGEXP = void 0;
const color_extractor_1 = require("../color-extractor");
const __strategy_base_1 = require("./__strategy-base");
const regexp_1 = require("../../util/regexp");
const color_1 = require("../color");
const HEXA_PREFIX = '(?:#|0x)';
exports.REGEXP = new RegExp(`(${HEXA_PREFIX}(?:${regexp_1.HEXA_VALUE}{3,4}|${regexp_1.HEXA_VALUE}{6}|${regexp_1.HEXA_VALUE}{8}))${regexp_1.EOL}`, 'gi');
exports.REGEXP_ONE = new RegExp(`^(${HEXA_PREFIX}(?:${regexp_1.HEXA_VALUE}{3,4}|${regexp_1.HEXA_VALUE}{6}|${regexp_1.HEXA_VALUE}{8}))${regexp_1.EOL}`, 'i');
function extractRGB(argb) {
let rgb = argb.slice(-6);
if (argb.length === 3 || argb.length === 4) {
const _argb = argb.slice(-3);
rgb = [_argb[0], _argb[0], _argb[1], _argb[1], _argb[2], _argb[2]];
}
return [16 * rgb[0] + rgb[1], 16 * rgb[2] + rgb[3], 16 * rgb[4] + rgb[5]];
}
function extractAlpha(argb) {
if (argb.length === 4) {
const alpha = argb[0];
return ((16 * alpha) + alpha) / 255;
}
if (argb.length === 8) {
const alpha = argb.slice(0, 2);
return ((16 * alpha[0]) + alpha[1]) / 255;
}
return 1;
}
function removePrefix(argb) {
return /(?:#|0x)(.+)/gi.exec(argb);
}
function hexaToInt(argb) {
return argb.split('').map(_ => parseInt(_, 16));
}
function getColor(match) {
const value = match[1];
const argb = removePrefix(value)[1];
const values = hexaToInt(argb);
const rgb = extractRGB(values);
const alpha = extractAlpha(values);
return new color_1.default(value, match.index, rgb, alpha);
}
const strategy = new __strategy_base_1.default('ARGB', exports.REGEXP, exports.REGEXP_ONE, getColor);
color_extractor_1.default.registerStrategy(strategy);
exports.default = strategy;
//# sourceMappingURL=argb-strategy.js.map

View File

@@ -0,0 +1,785 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.REGEXP_ONE = exports.REGEXP = exports.COLORS = void 0;
const color_1 = require("./../color");
const color_extractor_1 = require("../color-extractor");
const regexp_1 = require("../../util/regexp");
exports.COLORS = Object({
'aliceblue': {
value: '#F0F8FF',
rgb: [240, 248, 255],
luminace: 1
},
'antiquewhite': {
value: '#FAEBD7',
rgb: [250, 235, 215],
luminace: 1
},
'aqua': {
value: '#00FFFF',
rgb: [0, 255, 255],
luminace: 1
},
'aquamarine': {
value: '#7FFFD4',
rgb: [127, 255, 212],
luminace: 1
},
'azure': {
value: '#F0FFFF',
rgb: [240, 255, 255],
luminace: 1
},
'beige': {
value: '#F5F5DC',
rgb: [245, 245, 220],
luminace: 1
},
'bisque': {
value: '#FFE4C4',
rgb: [255, 228, 196],
luminace: 1
},
'black': {
value: '#000000',
rgb: [0, 0, 0],
luminace: 1
},
'blanchedalmond': {
value: '#FFEBCD',
rgb: [255, 235, 205],
luminace: 1
},
'blue': {
value: '#0000FF',
rgb: [0, 0, 255],
luminace: 1
},
'blueviolet': {
value: '#8A2BE2',
rgb: [138, 43, 226],
luminace: 1
},
'brown': {
value: '#A52A2A',
rgb: [165, 42, 42],
luminace: 1
},
'burlywood': {
value: '#DEB887',
rgb: [222, 184, 135],
luminace: 1
},
'cadetblue': {
value: '#5F9EA0',
rgb: [95, 158, 160],
luminace: 1
},
'chartreuse': {
value: '#7FFF00',
rgb: [127, 255, 0],
luminace: 1
},
'chocolate': {
value: '#D2691E',
rgb: [210, 105, 30],
luminace: 1
},
'coral': {
value: '#FF7F50',
rgb: [255, 127, 80],
luminace: 1
},
'cornflowerblue': {
value: '#6495ED',
rgb: [100, 149, 237],
luminace: 1
},
'cornsilk': {
value: '#FFF8DC',
rgb: [255, 248, 220],
luminace: 1
},
'crimson': {
value: '#DC143C',
rgb: [220, 20, 60],
luminace: 1
},
'cyan': {
value: '#00FFFF',
rgb: [0, 255, 255],
luminace: 1
},
'darkblue': {
value: '#00008B',
rgb: [0, 0, 139],
luminace: 1
},
'darkcyan': {
value: '#008B8B',
rgb: [0, 139, 139],
luminace: 1
},
'darkgoldenrod': {
value: '#B8860B',
rgb: [184, 134, 11],
luminace: 1
},
'darkgray': {
value: '#A9A9A9',
rgb: [169, 169, 169],
luminace: 1
},
'darkgrey': {
value: '#A9A9A9',
rgb: [169, 169, 169],
luminace: 1
},
'darkgreen': {
value: '#006400',
rgb: [0, 100, 0],
luminace: 1
},
'darkkhaki': {
value: '#BDB76B',
rgb: [189, 183, 107],
luminace: 1
},
'darkmagenta': {
value: '#8B008B',
rgb: [139, 0, 139],
luminace: 1
},
'darkolivegreen': {
value: '#556B2F',
rgb: [85, 107, 47],
luminace: 1
},
'darkorange': {
value: '#FF8C00',
rgb: [255, 140, 0],
luminace: 1
},
'darkorchid': {
value: '#9932CC',
rgb: [153, 50, 204],
luminace: 1
},
'darkred': {
value: '#8B0000',
rgb: [139, 0, 0],
luminace: 1
},
'darksalmon': {
value: '#E9967A',
rgb: [233, 150, 122],
luminace: 1
},
'darkseagreen': {
value: '#8FBC8F',
rgb: [143, 188, 143],
luminace: 1
},
'darkslateblue': {
value: '#483D8B',
rgb: [72, 61, 139],
luminace: 1
},
'darkslategray': {
value: '#2F4F4F',
rgb: [47, 79, 79],
luminace: 1
},
'darkslategrey': {
value: '#2F4F4F',
rgb: [47, 79, 79],
luminace: 1
},
'darkturquoise': {
value: '#00CED1',
rgb: [0, 206, 209],
luminace: 1
},
'darkviolet': {
value: '#9400D3',
rgb: [148, 0, 211],
luminace: 1
},
'deeppink': {
value: '#FF1493',
rgb: [255, 20, 147],
luminace: 1
},
'deepskyblue': {
value: '#00BFFF',
rgb: [0, 191, 255],
luminace: 1
},
'dimgray': {
value: '#696969',
rgb: [105, 105, 105],
luminace: 1
},
'dimgrey': {
value: '#696969',
rgb: [105, 105, 105],
luminace: 1
},
'dodgerblue': {
value: '#1E90FF',
rgb: [30, 144, 255],
luminace: 1
},
'firebrick': {
value: '#B22222',
rgb: [178, 34, 34],
luminace: 1
},
'floralwhite': {
value: '#FFFAF0',
rgb: [255, 250, 240],
luminace: 1
},
'forestgreen': {
value: '#228B22',
rgb: [34, 139, 34],
luminace: 1
},
'fuchsia': {
value: '#FF00FF',
rgb: [255, 0, 255],
luminace: 1
},
'gainsboro': {
value: '#DCDCDC',
rgb: [220, 220, 220],
luminace: 1
},
'ghostwhite': {
value: '#F8F8FF',
rgb: [248, 248, 255],
luminace: 1
},
'gold': {
value: '#FFD700',
rgb: [255, 215, 0],
luminace: 1
},
'goldenrod': {
value: '#DAA520',
rgb: [218, 165, 32],
luminace: 1
},
'gray': {
value: '#808080',
rgb: [128, 128, 128],
luminace: 1
},
'grey': {
value: '#808080',
rgb: [128, 128, 128],
luminace: 1
},
'green': {
value: '#008000',
rgb: [0, 128, 0],
luminace: 1
},
'greenyellow': {
value: '#ADFF2F',
rgb: [173, 255, 47],
luminace: 1
},
'honeydew': {
value: '#F0FFF0',
rgb: [240, 255, 240],
luminace: 1
},
'hotpink': {
value: '#FF69B4',
rgb: [255, 105, 180],
luminace: 1
},
'indianred': {
value: '#CD5C5C',
rgb: [205, 92, 92],
luminace: 1
},
'indigo': {
value: '#4B0082',
rgb: [75, 0, 130],
luminace: 1
},
'ivory': {
value: '#FFFFF0',
rgb: [255, 255, 240],
luminace: 1
},
'khaki': {
value: '#F0E68C',
rgb: [240, 230, 140],
luminace: 1
},
'lavender': {
value: '#E6E6FA',
rgb: [230, 230, 250],
luminace: 1
},
'lavenderblush': {
value: '#FFF0F5',
rgb: [255, 240, 245],
luminace: 1
},
'lawngreen': {
value: '#7CFC00',
rgb: [124, 252, 0],
luminace: 1
},
'lemonchiffon': {
value: '#FFFACD',
rgb: [255, 250, 205],
luminace: 1
},
'lightblue': {
value: '#ADD8E6',
rgb: [173, 216, 230],
luminace: 1
},
'lightcoral': {
value: '#F08080',
rgb: [240, 128, 128],
luminace: 1
},
'lightcyan': {
value: '#E0FFFF',
rgb: [224, 255, 255],
luminace: 1
},
'lightgoldenrodyellow': {
value: '#FAFAD2',
rgb: [250, 250, 210],
luminace: 1
},
'lightgray': {
value: '#D3D3D3',
rgb: [211, 211, 211],
luminace: 1
},
'lightgrey': {
value: '#D3D3D3',
rgb: [211, 211, 211],
luminace: 1
},
'lightgreen': {
value: '#90EE90',
rgb: [144, 238, 144],
luminace: 1
},
'lightpink': {
value: '#FFB6C1',
rgb: [255, 182, 193],
luminace: 1
},
'lightsalmon': {
value: '#FFA07A',
rgb: [255, 160, 122],
luminace: 1
},
'lightseagreen': {
value: '#20B2AA',
rgb: [32, 178, 170],
luminace: 1
},
'lightskyblue': {
value: '#87CEFA',
rgb: [135, 206, 250],
luminace: 1
},
'lightslategray': {
value: '#778899',
rgb: [119, 136, 153],
luminace: 1
},
'lightslategrey': {
value: '#778899',
rgb: [119, 136, 153],
luminace: 1
},
'lightsteelblue': {
value: '#B0C4DE',
rgb: [176, 196, 222],
luminace: 1
},
'lightyellow': {
value: '#FFFFE0',
rgb: [255, 255, 224],
luminace: 1
},
'lime': {
value: '#00FF00',
rgb: [0, 255, 0],
luminace: 1
},
'limegreen': {
value: '#32CD32',
rgb: [50, 205, 50],
luminace: 1
},
'linen': {
value: '#FAF0E6',
rgb: [250, 240, 230],
luminace: 1
},
'magenta': {
value: '#FF00FF',
rgb: [255, 0, 255],
luminace: 1
},
'maroon': {
value: '#800000',
rgb: [128, 0, 0],
luminace: 1
},
'mediumaquamarine': {
value: '#66CDAA',
rgb: [102, 205, 170],
luminace: 1
},
'mediumblue': {
value: '#0000CD',
rgb: [0, 0, 205],
luminace: 1
},
'mediumorchid': {
value: '#BA55D3',
rgb: [186, 85, 211],
luminace: 1
},
'mediumpurple': {
value: '#9370DB',
rgb: [147, 112, 219],
luminace: 1
},
'mediumseagreen': {
value: '#3CB371',
rgb: [60, 179, 113],
luminace: 1
},
'mediumslateblue': {
value: '#7B68EE',
rgb: [123, 104, 238],
luminace: 1
},
'mediumspringgreen': {
value: '#00FA9A',
rgb: [0, 250, 154],
luminace: 1
},
'mediumturquoise': {
value: '#48D1CC',
rgb: [72, 209, 204],
luminace: 1
},
'mediumvioletred': {
value: '#C71585',
rgb: [199, 21, 133],
luminace: 1
},
'midnightblue': {
value: '#191970',
rgb: [25, 25, 112],
luminace: 1
},
'mintcream': {
value: '#F5FFFA',
rgb: [245, 255, 250],
luminace: 1
},
'mistyrose': {
value: '#FFE4E1',
rgb: [255, 228, 225],
luminace: 1
},
'moccasin': {
value: '#FFE4B5',
rgb: [255, 228, 181],
luminace: 1
},
'navajowhite': {
value: '#FFDEAD',
rgb: [255, 222, 173],
luminace: 1
},
'navy': {
value: '#000080',
rgb: [0, 0, 128],
luminace: 1
},
'oldlace': {
value: '#FDF5E6',
rgb: [253, 245, 230],
luminace: 1
},
'olive': {
value: '#808000',
rgb: [128, 128, 0],
luminace: 1
},
'olivedrab': {
value: '#6B8E23',
rgb: [107, 142, 35],
luminace: 1
},
'orange': {
value: '#FFA500',
rgb: [255, 165, 0],
luminace: 1
},
'orangered': {
value: '#FF4500',
rgb: [255, 69, 0],
luminace: 1
},
'orchid': {
value: '#DA70D6',
rgb: [218, 112, 214],
luminace: 1
},
'palegoldenrod': {
value: '#EEE8AA',
rgb: [238, 232, 170],
luminace: 1
},
'palegreen': {
value: '#98FB98',
rgb: [152, 251, 152],
luminace: 1
},
'paleturquoise': {
value: '#AFEEEE',
rgb: [175, 238, 238],
luminace: 1
},
'palevioletred': {
value: '#DB7093',
rgb: [219, 112, 147],
luminace: 1
},
'papayawhip': {
value: '#FFEFD5',
rgb: [255, 239, 213],
luminace: 1
},
'peachpuff': {
value: '#FFDAB9',
rgb: [255, 218, 185],
luminace: 1
},
'peru': {
value: '#CD853F',
rgb: [205, 133, 63],
luminace: 1
},
'pink': {
value: '#FFC0CB',
rgb: [255, 192, 203],
luminace: 1
},
'plum': {
value: '#DDA0DD',
rgb: [221, 160, 221],
luminace: 1
},
'powderblue': {
value: '#B0E0E6',
rgb: [176, 224, 230],
luminace: 1
},
'purple': {
value: '#800080',
rgb: [128, 0, 128],
luminace: 1
},
'rebeccapurple': {
value: '#663399',
rgb: [102, 51, 153],
luminace: 1
},
'red': {
value: '#FF0000',
rgb: [255, 0, 0],
luminace: 1
},
'rosybrown': {
value: '#BC8F8F',
rgb: [188, 143, 143],
luminace: 1
},
'royalblue': {
value: '#4169E1',
rgb: [65, 105, 225],
luminace: 1
},
'saddlebrown': {
value: '#8B4513',
rgb: [139, 69, 19],
luminace: 1
},
'salmon': {
value: '#FA8072',
rgb: [250, 128, 114],
luminace: 1
},
'sandybrown': {
value: '#F4A460',
rgb: [244, 164, 96],
luminace: 1
},
'seagreen': {
value: '#2E8B57',
rgb: [46, 139, 87],
luminace: 1
},
'seashell': {
value: '#FFF5EE',
rgb: [255, 245, 238],
luminace: 1
},
'sienna': {
value: '#A0522D',
rgb: [160, 82, 45],
luminace: 1
},
'silver': {
value: '#C0C0C0',
rgb: [192, 192, 192],
luminace: 1
},
'skyblue': {
value: '#87CEEB',
rgb: [135, 206, 235],
luminace: 1
},
'slateblue': {
value: '#6A5ACD',
rgb: [106, 90, 205],
luminace: 1
},
'slategray': {
value: '#708090',
rgb: [112, 128, 144],
luminace: 1
},
'slategrey': {
value: '#708090',
rgb: [112, 128, 144],
luminace: 1
},
'snow': {
value: '#FFFAFA',
rgb: [255, 250, 250],
luminace: 1
},
'springgreen': {
value: '#00FF7F',
rgb: [0, 255, 127],
luminace: 1
},
'steelblue': {
value: '#4682B4',
rgb: [70, 130, 180],
luminace: 1
},
'tan': {
value: '#D2B48C',
rgb: [210, 180, 140],
luminace: 1
},
'teal': {
value: '#008080',
rgb: [0, 128, 128],
luminace: 1
},
'thistle': {
value: '#D8BFD8',
rgb: [216, 191, 216],
luminace: 1
},
'tomato': {
value: '#FF6347',
rgb: [255, 99, 71],
luminace: 1
},
'turquoise': {
value: '#40E0D0',
rgb: [64, 224, 208],
luminace: 1
},
'violet': {
value: '#EE82EE',
rgb: [238, 130, 238],
luminace: 1
},
'wheat': {
value: '#F5DEB3',
rgb: [245, 222, 179],
luminace: 1
},
'white': {
value: '#FFFFFF',
rgb: [255, 255, 255],
luminace: 1
},
'whitesmoke': {
value: '#F5F5F5',
rgb: [245, 245, 245],
luminace: 1
},
'yellow': {
value: '#FFFF00',
rgb: [255, 255, 0],
luminace: 1
},
'yellowgreen': {
value: '#9ACD32',
rgb: [154, 205, 50],
luminace: 1
}
});
const REGEXP_BASE = Object.keys(exports.COLORS).map((color) => `(?:${color.toLowerCase()})`).join('|');
exports.REGEXP = (() => RegExp(`(?:,| |'|"|\\(|:)(${REGEXP_BASE})${regexp_1.EOL}`, 'i'))();
// export const REGEXP_ONE = (() => RegExp(`^(?:,| |\\(|:)(${Object.keys(COLORS).map((color) => `(?:${color.toLowerCase()})`).join('|')})(?:$|,| |;|\\)|\\r|\\n)`, 'i'))();
// Checking for beginning beginning allow to catch stylus var value
// eslint-disable-next-line
exports.REGEXP_ONE = (() => RegExp(`^(?:^|,|\s|\\(|:)(${REGEXP_BASE})${regexp_1.EOL}`, 'i'))();
class BrowsersColorExtractor {
constructor() {
this.name = 'BROWSERS_COLORS';
}
async extractColors(fileLines) {
return fileLines.map(({ line, text }) => {
let match = null;
const colors = [];
let position = 0;
while ((match = text.match(exports.REGEXP)) !== null) {
position += match.index + 1;
const browserColor = match[1];
colors.push(new color_1.default(match[1], position, exports.COLORS[browserColor.toLowerCase()].rgb));
text = text.slice(match.index + 1 + match[1].length);
position += match[1].length;
}
return { line, colors };
});
}
extractColor(text) {
const match = text.match(exports.REGEXP_ONE);
if (match) {
const browserColor = match[1];
return new color_1.default(match[1], match.index, exports.COLORS[browserColor.toLowerCase()].rgb);
}
return null;
}
}
color_extractor_1.default.registerStrategy(new BrowsersColorExtractor());
exports.default = BrowsersColorExtractor;
//# sourceMappingURL=browser-strategy.js.map

View File

@@ -0,0 +1,47 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.REGEXP_ONE = exports.REGEXP = void 0;
const color_extractor_1 = require("../color-extractor");
const __strategy_base_1 = require("./__strategy-base");
const regexp_1 = require("../../util/regexp");
const color_1 = require("../color");
const HEXA_PREFIX = '(?:#|0x)';
exports.REGEXP = new RegExp(`(${HEXA_PREFIX}(?:${regexp_1.HEXA_VALUE}{3,4}|${regexp_1.HEXA_VALUE}{6}|${regexp_1.HEXA_VALUE}{8}))${regexp_1.EOL}`, 'gi');
exports.REGEXP_ONE = new RegExp(`^(${HEXA_PREFIX}(?:${regexp_1.HEXA_VALUE}{3,4}|${regexp_1.HEXA_VALUE}{6}|${regexp_1.HEXA_VALUE}{8}))${regexp_1.EOL}`, 'i');
function extractRGB(values) {
let rgb = values.slice(0, 6);
if (values.length === 3 || values.length === 4) {
const _rgb = values.slice(0, 3);
rgb = [_rgb[0], _rgb[0], _rgb[1], _rgb[1], _rgb[2], _rgb[2]];
}
return [16 * rgb[0] + rgb[1], 16 * rgb[2] + rgb[3], 16 * rgb[4] + rgb[5]];
}
function extractAlpha(values) {
if (values.length === 4) {
const alpha = values[3];
return ((16 * alpha) + alpha) / 255;
}
if (values.length === 8) {
const alpha = values.slice(6, 8);
return ((16 * alpha[0]) + alpha[1]) / 255;
}
return 1;
}
function removePrefix(argb) {
return /(?:#|0x)(.+)/gi.exec(argb);
}
function hexaToInt(argb) {
return argb.split('').map(_ => parseInt(_, 16));
}
function getColor(match) {
const value = match[1];
const str = removePrefix(value)[1];
const values = hexaToInt(str);
const rgb = extractRGB(values);
const alpha = extractAlpha(values);
return new color_1.default(value, match.index, rgb, alpha);
}
const strategy = new __strategy_base_1.default('HEXA', exports.REGEXP, exports.REGEXP_ONE, getColor);
color_extractor_1.default.registerStrategy(strategy);
exports.default = strategy;
//# sourceMappingURL=hexa-strategy.js.map

View File

@@ -0,0 +1,38 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.REGEXP_ONE = exports.REGEXP = void 0;
const color_1 = require("./../color");
const color_extractor_1 = require("../color-extractor");
const color_util_1 = require("../../util/color-util");
const regexp_1 = require("../../util/regexp");
const __strategy_base_1 = require("./__strategy-base");
const R_HUE = `\\d*${regexp_1.DOT_VALUE}?`;
const R_SATURATION = `(?:\\d{1,3}${regexp_1.DOT_VALUE}?|${regexp_1.DOT_VALUE})%`;
const R_LUMINANCE = R_SATURATION;
exports.REGEXP = new RegExp(`((?:hsl\\(\\s*${R_HUE}\\s*,\\s*${R_SATURATION}\\s*,\\s*${R_LUMINANCE}\\s*\\))|(?:hsla\\(\\s*${R_HUE}\\s*,\\s*${R_SATURATION}\\s*,\\s*${R_LUMINANCE}\\s*,\\s*${regexp_1.ALPHA}\\s*\\)))${regexp_1.EOL}`, 'gi');
exports.REGEXP_ONE = new RegExp(`^((?:hsl\\(\\s*${R_HUE}\\s*,\\s*${R_SATURATION}\\s*,\\s*${R_LUMINANCE}\\s*\\))|(?:hsla\\(\\s*${R_HUE}\\s*,\\s*${R_SATURATION}\\s*,\\s*${R_LUMINANCE}\\s*,\\s*${regexp_1.ALPHA}\\s*\\)))${regexp_1.EOL}`, 'i');
// export const REGEXP_ONE = /^((?:hsl\(\d*\s*,\s*\d{1,3}%\s*,\s*\d{1,3}%\))|(?:hsla\(\d*\s*,\s*(?:\d{1,3}%\s*,\s*){2}(?:[0-1]|1\.0|[0](?:\.\d+){0,1}|(?:\.\d+))\)))(?:$|"|'|,| |;|\)|\r|\n)/i;
/**
* @private
* @param {any} value An hsl(a) color string (`hsl(10, 1%, 1%)`)
* @returns {number[]} The colors h,s,l,a values
*
* @memberof HSLColorExtractor
*/
function extractHSLValue(value) {
const [h, s, l, a] = value.replace(/hsl(a){0,1}\(/, '').replace(/\)/, '').replace(/%/g, '').split(/,/gi).map(c => parseFloat(c));
return [h, s, l, a];
}
function getColor(match) {
const value = match[0];
const [h, s, l, a] = extractHSLValue(value);
if (s <= 100 && l <= 100) {
const [r, g, b] = color_util_1.convertHslaToRgba(h, s, l, a);
return new color_1.default(match[1], match.index, [r, g, b], a);
}
return null;
}
const strategy = new __strategy_base_1.default('HSL', exports.REGEXP, exports.REGEXP_ONE, getColor);
color_extractor_1.default.registerStrategy(strategy);
exports.default = strategy;
//# sourceMappingURL=hsl-strategy.js.map

View File

@@ -0,0 +1,30 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.REGEXP_ONE = exports.REGEXP = void 0;
const color_extractor_1 = require("../color-extractor");
const color_1 = require("../color");
const regexp_1 = require("../../util/regexp");
const __strategy_base_1 = require("./__strategy-base");
const R_RED = `(?:\\d{1,3}${regexp_1.DOT_VALUE}?|${regexp_1.DOT_VALUE})`;
const R_GREEN = R_RED;
const R_BLUE = R_RED;
exports.REGEXP = new RegExp(`((?:rgb\\(\\s*${R_RED}\\s*,\\s*${R_GREEN}\\s*,\\s*${R_BLUE}\\s*\\))|(?:rgba\\(\\s*${R_RED}\\s*,\\s*${R_GREEN}\\s*,\\s*${R_BLUE}\\s*,\\s*${regexp_1.ALPHA}\\s*\\)))${regexp_1.EOL}`, 'gi');
exports.REGEXP_ONE = new RegExp(`^((?:rgb\\(\\s*${R_RED}\\s*,\\s*${R_GREEN}\\s*,\\s*${R_BLUE}\\s*\\))|(?:rgba\\(\\s*${R_RED}\\s*,\\s*${R_GREEN}\\s*,\\s*${R_BLUE}\\s*,\\s*${regexp_1.ALPHA}\\s*\\)))${regexp_1.EOL}`, 'i');
function extractRGBA(value) {
const rgba_string = value.replace(/rgb(a){0,1}\(/, '').replace(/\)/, '');
return rgba_string.split(/,/gi).map(c => parseFloat(c));
}
function getColor(match) {
const value = match[1];
const rgba = extractRGBA(value);
const alpha = rgba[3] || 1;
const rgb = rgba.slice(0, 3);
// Check if it's a valid rgb(a) color
if (rgb.every(c => c <= 255)) {
return new color_1.default(match[1], match.index, rgb, alpha);
}
return null;
}
const strategy = new __strategy_base_1.default('RGB', exports.REGEXP, exports.REGEXP_ONE, getColor);
color_extractor_1.default.registerStrategy(strategy);
//# sourceMappingURL=rgb-strategy.js.map

View File

@@ -0,0 +1,46 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class EditorManager {
/**
* Run through a list of decorations to generate editor's decorations
*
* @static
* @param {TextEditor} editor
* @param {Map<number, IDecoration[]>} decorations
* @param {number[]} skipLines
* @returns
* @memberof EditorManager
*/
static decorate(editor, decorations, skipLines) {
const it = decorations.entries();
let tmp = it.next();
while (!tmp.done) {
const line = tmp.value[0];
const deco = tmp.value[1];
if (skipLines.indexOf(line) === -1) {
this.decorateOneLine(editor, deco, line);
}
tmp = it.next();
}
return;
}
// Decorate editor's decorations for one line
/**
* Generate decorations in one line for the selected editor
*
* @static
* @param {TextEditor} editor
* @param {IDecoration[]} decorations
* @param {number} line
* @memberof EditorManager
*/
static decorateOneLine(editor, decorations, line) {
decorations.forEach((decoration) => {
if (decoration.shouldGenerateDecoration() === true) {
editor.setDecorations(decoration.decoration, [decoration.generateRange(line)]);
}
});
}
}
exports.default = EditorManager;
//# sourceMappingURL=editor-manager.js.map

View File

@@ -0,0 +1,64 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Extractor = void 0;
class Extractor {
constructor() {
this.strategies = [];
}
enableStrategies(strategiesToEnable) {
this.enabledStrategies = this.strategies.filter(strategy => {
if (strategiesToEnable.find(_ => _ === strategy.name)) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const constructor = strategy.constructor;
return new constructor();
}
});
}
registerStrategy(strategy) {
if (!this.has(strategy)) {
this.strategies.push(strategy);
}
}
has(strategy) {
if (typeof strategy === 'string') {
return this.strategies.some(_ => _.name === strategy);
}
return this.strategies.some(_ => _.name === strategy.name);
}
get(strategy) {
if (this.has(strategy) === false) {
return null;
}
return this.strategies.find(_ => _.name === strategy);
}
}
exports.Extractor = Extractor;
// Use mixin instead?
// type Constructor<T = {}> = new (...args: any[]) => T;
// export function TExtractor<TBase extends Constructor>(Base: TBase) {
// return class TExtractor extends Base {
// public extractors: IStrategy[];
// constructor(...args: any[]) {
// super(...args);
// this.extractors = [];
// }
// public registerExtractor(extractor: IStrategy) {
// if (!this.has(extractor)) {
// this.extractors.push(extractor);
// }
// }
// public has(extractor: string | IStrategy): boolean {
// if (typeof extractor === 'string') {
// return this.extractors.some(_ => _.name === extractor);
// }
// return this.extractors.some(_ => _.name === extractor.name);
// }
// public get(extractor: string | IStrategy): IStrategy {
// if (this.has(extractor) === false) {
// return null;
// }
// return this.extractors.find(_ => _.name === extractor);
// }
// };
// }
//# sourceMappingURL=extractor-mixin.js.map

View File

@@ -0,0 +1,40 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class Queue {
constructor() {
this._running = false;
this._queue = [];
}
/**
* Add a action inside the queue.
* The action should take a callback as first parameter and call it
* when his work is done in order to start the next action
*
* @param {Function} f
* @returns
* @memberOf Queue
*/
push(f) {
this._queue.push(f);
if (!this._running) {
// if nothing is running, then start the engines!
this._next();
}
return this; // for chaining fun!
}
_next() {
this._running = false;
const action = this._queue.shift();
if (action) {
this._running = true;
try {
action(this._next.bind(this));
}
catch (error) {
this._next.call(this);
}
}
}
}
exports.default = Queue;
//# sourceMappingURL=queue.js.map

View File

@@ -0,0 +1,54 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class TasksRunner {
constructor() {
this._currentTask = null;
}
/**
* Add a task to run.
* Pushing a new task will cancel the execution of the previous
*
* @param {Generator} IterableIterator<any>
* @returns
* @memberOf TasksRunner
*/
run(f) {
if (this._currentTask) {
this._currentTask.return();
}
this._currentTask = f();
this._run();
return this; // for chaining fun!
}
/**
* Cancel the currently running task
*
* @memberOf TasksRunner
*/
stop() {
if (this._currentTask) {
this._currentTask.return();
}
}
_run() {
const it = this._currentTask;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function run(args) {
try {
const result = it.next(args); // deal with errors in generators
if (result.done) {
return result.value;
}
else {
return Promise.resolve(result.value).then(run);
}
}
catch (error) {
// do something
}
}
run();
}
}
exports.default = TasksRunner;
//# sourceMappingURL=tasks-runner.js.map

View File

@@ -0,0 +1,27 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.equals = exports.unique = void 0;
function unique(arr, f) {
let vArr = arr;
if (f) {
vArr = arr.map(f);
}
return arr.filter((_, i) => vArr.indexOf(vArr[i]) === i);
}
exports.unique = unique;
function equals(arr1, arr2) {
if (arr1 === null || arr2 === null) {
return false;
}
if (arr1.length !== arr2.length) {
return false;
}
for (const i in arr1) {
if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
}
exports.equals = equals;
//# sourceMappingURL=array.js.map

View File

@@ -0,0 +1,178 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.flattenLineExtractionsFlatten = exports.generateOptimalTextColor = exports.convertRgbaToHsla = exports.colorLuminance = exports.convertHslaToRgba = void 0;
require("../colors/strategies/hexa-strategy");
require("../colors/strategies/argb-strategy");
require("../colors/strategies/rgb-strategy");
require("../colors/strategies/browser-strategy");
require("../colors/strategies/hsl-strategy");
const color_extractor_1 = require("../colors/color-extractor");
const color_decoration_1 = require("../colors/color-decoration");
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
const flattenLineExtractionsFlatten = arr => arr.flat(2).filter(_ => _.colors.length !== 0);
exports.flattenLineExtractionsFlatten = flattenLineExtractionsFlatten;
const WHITE = '#FFFFFF', BLACK = '#000000';
class ColorUtil {
static textToFileLines(text) {
return text.split(/\n/)
.map((text, index) => Object({
'text': text,
'line': index
}));
}
/**
* Extract all colors from a text
*
* @static
* @param {any} text
* @returns {Promise < Color[] >}
*
* @memberOf ColorUtil
*/
static findColors(fileContent) {
return color_extractor_1.default.extract(fileContent);
}
static setupColorsExtractors(extractors) {
color_extractor_1.default.enableStrategies(extractors);
}
static generateDecoration(color, line, decorationFn) {
return new color_decoration_1.default(color, line, decorationFn);
}
}
/**
* Generate the color luminance.
* The luminance value is between 0 and 1
* - 1 means that the color is light
* - 0 means that the color is dark
*
* @static
* @param {Color} color
* @returns {number}
*/
function colorLuminance(color) {
const rgb = color.rgb.map(c => {
c = c / 255;
if (c < 0.03928) {
c = c / 12.92;
}
else {
c = (c + .055) / 1.055;
c = Math.pow(c, 2.4);
}
return c;
});
return (0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]);
}
exports.colorLuminance = colorLuminance;
function generateOptimalTextColor(color) {
const luminance = colorLuminance(color);
const contrastRatioBlack = (luminance + 0.05) / 0.05;
if (contrastRatioBlack > 7) {
return BLACK;
}
const contrastRatioWhite = 1.05 / (luminance + 0.05);
if (contrastRatioWhite > 7) {
return WHITE;
}
if (contrastRatioBlack > contrastRatioWhite) {
return BLACK;
}
return WHITE;
}
exports.generateOptimalTextColor = generateOptimalTextColor;
/**
* Converts an RGB color value to HSL. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
*
* @param {number} r The red color value
* @param {number} g The green color value
* @param {number} b The blue color value
* @param {number} a The alpha value
*
* @return {[number, number, number, number]} [h,s,l,a] - The HSLa representation
*/
function convertRgbaToHsla(r, g, b, a = 1) {
r /= 255, g /= 255, b /= 255;
const max = Math.max(r, g, b), min = Math.min(r, g, b);
let h;
const l = (max + min) / 2;
if (max === min) {
return [0, 0, Math.round(l * 100), a]; // achromatic
}
const d = max - min;
const s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
break;
}
h /= 6;
return [Math.round(360 * h), Math.round(100 * s), Math.round(l * 100), a];
}
exports.convertRgbaToHsla = convertRgbaToHsla;
/**
* Converts an HSLa color value to RGBa. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
*
* @param {number} h - The hue
* @param {number} s - The saturation
* @param {number} l - The lightness
* @param {number} a - The alpha
*
* @return {[number, number, number, number]} [r,g,b,a] - The RGBa representation
*/
function convertHslaToRgba(h, s, l, a = 1) {
let r, g, b;
if (s === 0) {
r = g = b = Math.round((l / 100) * 255);
return [r, g, b, a];
}
l = l / 100;
s = s / 100;
const tmp_1 = (l < 0.5) ? l * (1.0 + s) : l + s - l * s;
const temp_2 = 2 * l - tmp_1;
h = (h % 360) / 360;
const tmp_r = (h + 0.333) % 1;
const tmp_g = h;
let tmp_b = h - 0.333;
if (tmp_b < 0) {
tmp_b = tmp_b + 1;
}
r = executeHSLProperFormula(tmp_1, temp_2, tmp_r);
g = executeHSLProperFormula(tmp_1, temp_2, tmp_g);
b = executeHSLProperFormula(tmp_1, temp_2, tmp_b);
return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255), a];
}
exports.convertHslaToRgba = convertHslaToRgba;
/**
* Select and execute the proper formula to get the r,g,b values
*
* @private
* @param {number} tmp_1
* @param {number} tmp_2
* @param {number} value
* @returns {number}
*
* @memberof HSLColorExtractor
*/
function executeHSLProperFormula(tmp_1, tmp_2, value) {
const res = tmp_2;
if (6 * value < 1) {
return tmp_2 + (tmp_1 - tmp_2) * 6 * value;
}
if (2 * value < 1) {
return tmp_1;
}
if (3 * value < 2) {
return tmp_2 + (tmp_1 - tmp_2) * ((2 / 3) - value) * 6;
}
return res;
}
exports.default = ColorUtil;
//# sourceMappingURL=color-util.js.map

View File

@@ -0,0 +1,61 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.mutEditedLine = void 0;
const vscode_1 = require("vscode");
// Split the TextDocumentContentChangeEvent into multiple line if the added text contain multiple lines
// example :
// let editedLine = [{
// rangeLength: 0,
// text: 'a\nb\nc\n',
// range: {start:{line:1}, end:{line:1}}
// }]
// became
// let editedLine = [{
// rangeLength: 0,
// text: 'a',
// range: {start:{line:1,/*...*/}, end:{line:1,/*...*/}}
// }, {
// rangeLength: 0,
// text: 'b',
// range: {start:{line:2,/*...*/}, end:{line:2,/*...*/}}
// }, {
// rangeLength: 0,
// text: 'c',
// range: {start:{line:3,/*...*/}, end:{line:3,/*...*/}}
// }, {
// rangeLength: 0,
// text: '',
// range: {start:{line:4,/*...*/}, end:{line:4,/*...*/}}
// }]
//
function mutEditedLine(editedLine) {
const newEditedLine = [];
let startLine = 0;
let before = 0;
editedLine.reverse();
editedLine.forEach(line => {
startLine = line.range.start.line + before;
line.text.split(/\n/).map((text, i, array) => {
if (i === 0 && text === '' && array.length === 1) {
startLine++;
}
else {
newEditedLine.push(generateTextDocumentContentChange(startLine++, text));
}
before++;
});
before--;
});
return newEditedLine;
}
exports.mutEditedLine = mutEditedLine;
// Generate a TextDocumentContentChangeEvent like object for one line
function generateTextDocumentContentChange(line, text) {
return {
rangeLength: 0,
rangeOffset: 0,
text: text,
range: new vscode_1.Range(new vscode_1.Position(line, 0), new vscode_1.Position(line, text.length))
};
}
//# sourceMappingURL=mut-edited-line.js.map

View File

@@ -0,0 +1,13 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HEXA_VALUE = exports.DOT_VALUE = exports.ALPHA = exports.EOL = void 0;
// eslint-disable-next-line
const EOL = `(?:$|\`|"|'|,| |;|\\)|\\r|\\n|\}|<)`;
exports.EOL = EOL;
const DOT_VALUE = '(?:\\.\\d+)'; // ['.x', '']
exports.DOT_VALUE = DOT_VALUE;
const ALPHA = `(?:1(:?\\.0+)?|0${DOT_VALUE}?|${DOT_VALUE})`; // ['0', '1', '0.x', '1.0', '.x']
exports.ALPHA = ALPHA;
const HEXA_VALUE = '[\\da-f]'; // [1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F']
exports.HEXA_VALUE = HEXA_VALUE;
//# sourceMappingURL=regexp.js.map

View File

@@ -0,0 +1,93 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const variable_1 = require("../variable");
const color_1 = require("../../colors/color");
const variable_store_1 = require("../variable-store");
const color_extractor_1 = require("../../colors/color-extractor");
const color_util_1 = require("../../util/color-util");
class VariableStrategy {
constructor(name, DECLARATION_REGEXP, USES_REGEXP, USE_REGEXP, regexpExtractor) {
this.name = name;
this.DECLARATION_REGEXP = DECLARATION_REGEXP;
this.USES_REGEXP = USES_REGEXP;
this.USE_REGEXP = USE_REGEXP;
this.regexpExtractor = regexpExtractor;
this.store = new variable_store_1.default();
}
async extractDeclarations(fileName, fileLines) {
return fileLines.map(({ text, line }) => this.__extractDeclarations(fileName, text, line)).length;
}
__extractDeclarations(fileName, text, line) {
let match = null;
while ((match = this.DECLARATION_REGEXP.exec(text)) !== null) {
const varName = this.regexpExtractor.getVariableNameFromDeclaration(match);
const color = color_extractor_1.default.extractOneColor(text.slice(match.index + match[0].length).trim()) || this.extractVariable(fileName, text.slice(match.index + match[0].length).trim());
if (this.store.has(varName, fileName, line)) {
const decoration = this.store.findDeclaration(varName, fileName, line);
decoration.update(color);
}
else {
const variable = new variable_1.default(varName, color, { fileName, line, position: match.index }, this.name);
this.store.addEntry(varName, variable); // update entry?? // outside ?
}
}
}
extractVariables(fileName, fileLines) {
const variables = fileLines.map(({ line, text }) => {
let match = null;
const colors = [];
while ((match = this.USES_REGEXP.exec(text)) !== null) {
const [varName, extendedVarName, spaces] = this.regexpExtractor.getVariableNameFromUses(match);
const spacesCount = (spaces || '').length;
const location = { fileName, line, position: spacesCount + match.index };
const variable = new variable_1.default(varName, new color_1.default(extendedVarName || varName, spacesCount + match.index, null, null), location, this.name);
colors.push(variable);
}
return { line, colors };
});
return color_util_1.flattenLineExtractionsFlatten(variables);
}
extractVariable(fileName, text) {
const match = text.match(this.USE_REGEXP);
let variable;
if (match) {
const varName = this.regexpExtractor.getVariableNameFromUse(match);
variable = this.store.findClosestDeclaration(varName, fileName);
// variable = this.store.findClosestDeclaration(match[2], fileName);
return variable ? variable.color : undefined;
}
}
/**
* Return the value (color) of a variable.
* The value is determined by searching the nearest variable declaration
* @param {Variable} variable
* @returns {Color|null}
*/
getVariableValue(variable) {
let color = null;
if (this.store.has(variable.name) === true) {
let declaration = this.store.findClosestDeclaration(variable.name, variable.location.fileName);
if (declaration.color === undefined) {
declaration = this.store.findClosestDeclaration(variable.name, '.');
}
if (declaration.color) {
color = new color_1.default(variable.color.value, variable.location.position, declaration.color.rgb, declaration.color.alpha);
}
}
return color;
}
variablesCount() {
return this.store.count;
}
deleteVariable(fileName, line) {
this.store.delete(null, fileName, line);
}
}
exports.default = VariableStrategy;
// Use mixin instead?
// type Constructor<T = {}> = new (...args: any[]) => T;
// export function TExtractor<TBase extends Constructor>(Base: TBase) {
// return class TExtractor extends Base {
// };
// }
//# sourceMappingURL=__strategy-base.js.map

View File

@@ -0,0 +1,34 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DECLARATION_REGEXP = exports.REGEXP_ONE = exports.REGEXP = void 0;
const variables_extractor_1 = require("../variables-extractor");
const regexp_1 = require("../../util/regexp");
const __strategy_base_1 = require("./__strategy-base");
// eslint-disable-next-line
exports.REGEXP = new RegExp(`(var\\((--(?:[a-z]+[\-_a-z\\d]*))\\))(?!:)${regexp_1.EOL}`, 'gi');
// eslint-disable-next-line
exports.REGEXP_ONE = new RegExp(`^(var\\((--(?:[a-z]+[\-_a-z\\d]*))\\))(?!:)${regexp_1.EOL}`, 'i');
exports.DECLARATION_REGEXP = new RegExp(`(?:(--(?:[a-z]+[\\-_a-z\\d]*)\\s*):)${regexp_1.EOL}`, 'gi');
const RegexpExtractor = {
getVariableNameFromDeclaration(match) {
return (match[1] || match[2]).trim();
},
getVariableNameFromUses(match) {
return [match[2].trim(), match[1].trim()];
},
getVariableNameFromUse(match) {
return match[2].trim();
}
};
const CssExtractor = new __strategy_base_1.default('CSS', exports.DECLARATION_REGEXP, exports.REGEXP, exports.REGEXP_ONE, RegexpExtractor);
variables_extractor_1.default.registerStrategy(CssExtractor);
exports.default = CssExtractor;
// ------------------------------------------------------------
// ------------------------------------------------------------
//
// THIS IS VALID
// --val: 20%, 10%, 1
// hsl(var(--val))
// hsla(var(--val), .3)
// TODO
//# sourceMappingURL=css-strategy.js.map

View File

@@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DECLARATION_REGEXP = exports.REGEXP_ONE = exports.REGEXP = void 0;
const variables_extractor_1 = require("../variables-extractor");
const regexp_1 = require("../../util/regexp");
const __strategy_base_1 = require("./__strategy-base");
exports.REGEXP = new RegExp(`(@(?:[a-z]+[\\-_a-z\\d]*)(?!:))${regexp_1.EOL}`, 'gi');
exports.REGEXP_ONE = new RegExp(`^(@(?:[a-z]+[\\-_a-z\\d]*)(?!:))${regexp_1.EOL}`, 'i');
exports.DECLARATION_REGEXP = new RegExp(`(?:(@(?:[a-z]+[\\-_a-z\\d]*)\\s*):)${regexp_1.EOL}`, 'gi');
const RegexpExtractor = {
getVariableNameFromDeclaration(match) {
return (match[1] || match[2]).trim();
},
getVariableNameFromUses(match) {
return [match[1].trim()];
},
getVariableNameFromUse(match) {
return match[1].trim();
}
};
variables_extractor_1.default.registerStrategy(new __strategy_base_1.default('LESS', exports.DECLARATION_REGEXP, exports.REGEXP, exports.REGEXP_ONE, RegexpExtractor));
//# sourceMappingURL=less-strategy.js.map

View File

@@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DECLARATION_REGEXP = exports.REGEXP_ONE = exports.REGEXP = void 0;
const variables_extractor_1 = require("../variables-extractor");
const regexp_1 = require("../../util/regexp");
const __strategy_base_1 = require("./__strategy-base");
exports.REGEXP = new RegExp(`(\\$(?:[_a-z]+[\\-_a-z\\d]*)(?!:))${regexp_1.EOL}`, 'gi');
exports.REGEXP_ONE = new RegExp(`^(\\$(?:[_a-z]+[\\-_a-z\\d]*)(?!:))${regexp_1.EOL}`, 'i');
exports.DECLARATION_REGEXP = new RegExp(`(?:(\\$(?:[_a-z]+[\\-_a-z\\d]*)\\s*):)${regexp_1.EOL}`, 'gi');
const RegexpExtractor = {
getVariableNameFromDeclaration(match) {
return (match[1] || match[2]).trim();
},
getVariableNameFromUses(match) {
return [match[1].trim()];
},
getVariableNameFromUse(match) {
return match[1].trim();
}
};
variables_extractor_1.default.registerStrategy(new __strategy_base_1.default('SASS', exports.DECLARATION_REGEXP, exports.REGEXP, exports.REGEXP_ONE, RegexpExtractor));
//# sourceMappingURL=sass-strategy.js.map

View File

@@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DECLARATION_REGEXP = exports.REGEXP_ONE = exports.REGEXP = void 0;
const variables_extractor_1 = require("../variables-extractor");
const regexp_1 = require("../../util/regexp");
const __strategy_base_1 = require("./__strategy-base");
exports.REGEXP = new RegExp(`(^|(?::|=)\\s*)((?:[\\-]*[$a-z_][\\-_\\d]*)+)(?!=)${regexp_1.EOL}`, 'gi');
exports.REGEXP_ONE = new RegExp(`(^|(?::|=)\\s*)((?:[\\-]*[$a-z_][\\-_\\d]*)+)(?!=)${regexp_1.EOL}`, 'i');
exports.DECLARATION_REGEXP = new RegExp(`(?:(^(?:\\$|(?:[\\-_$]+[a-z\\d]+)|(?:[^\\d||\\-|@]+))(?:[_a-z\\d][\\-]*)*))\\s*=${regexp_1.EOL}`, 'gi');
const RegexpExtractor = {
getVariableNameFromDeclaration(match) {
return (match[1] || match[2]).trim();
},
getVariableNameFromUses(match) {
return [match[2].trim(), null, match[1]];
},
getVariableNameFromUse(match) {
return match[2].trim();
}
};
variables_extractor_1.default.registerStrategy(new __strategy_base_1.default('STYLUS', exports.DECLARATION_REGEXP, exports.REGEXP, exports.REGEXP_ONE, RegexpExtractor));
//# sourceMappingURL=stylus-strategy.js.map

View File

@@ -0,0 +1,95 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const vscode_1 = require("vscode");
const variables_manager_1 = require("./variables-manager");
class VariableDecoration {
constructor(variable, line, decorationFn) {
/**
* Keep track of the TextEditorDecorationType status
*
* @type {boolean}
* @public
* @memberOf ColorDecoration
*/
this.disposed = false;
this.hidden = false;
this.variable = variable;
this.decorationFn = decorationFn;
if (this.variable.color) {
this.generateRange(line);
}
else {
this.currentRange = new vscode_1.Range(new vscode_1.Position(line, 0), new vscode_1.Position(line, 0));
}
}
/**
* The TextEditorDecorationType associated to the color
*
* @type {TextEditorDecorationType}
* @memberOf ColorDecoration
*/
get decoration() {
this._generateDecorator();
return this._decoration;
}
set decoration(deco) {
this._decoration = deco;
}
get rgb() {
return this.variable.color.rgb;
}
/**
* Disposed the TextEditorDecorationType
* (destroy the colored background)
*
* @public
* @memberOf ColorDecoration
*/
dispose() {
try {
this._decoration.dispose();
this.variable.color.rgb = null;
}
catch (error) {
// do something
}
this.disposed = true;
}
hide() {
if (this._decoration) {
this._decoration.dispose();
}
this.hidden = true;
}
/**
* Generate the decoration Range (start and end position in line)
*
* @param {number} line
* @returns {Range}
*
* @memberOf ColorDecoration
*/
generateRange(line) {
const range = new vscode_1.Range(new vscode_1.Position(line, this.variable.color.positionInText), new vscode_1.Position(line, this.variable.color.positionInText + this.variable.color.value.length));
this.currentRange = range;
return range;
}
shouldGenerateDecoration() {
const color = variables_manager_1.default.findVariable(this.variable);
if (this.disposed === true || color === null) {
return false;
}
return (this._decoration === null || this._decoration === undefined || this.hidden);
}
_generateDecorator() {
const color = variables_manager_1.default.findVariable(this.variable);
if (color && this.variable.color !== color) {
this.variable.color = color;
}
if (this.variable.color && this.variable.color.rgb) {
this._decoration = this.decorationFn(this.variable.color);
}
}
}
exports.default = VariableDecoration;
//# sourceMappingURL=variable-decoration.js.map

View File

@@ -0,0 +1,132 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const color_1 = require("../colors/color");
const path_1 = require("path");
class VariablesStore {
constructor() {
this.entries = new Map();
}
has(variable = null, fileName = null, line = null) {
const declarations = this.get(variable, fileName, line);
return declarations && declarations.length > 0;
}
get(variable, fileName = null, line = null) {
let decorations = this.entries.get(variable) || [];
if (fileName !== null) {
decorations = decorations.filter(_ => _.location.fileName === fileName);
}
if (line !== null) {
decorations = decorations.filter(_ => _.location.line === line);
}
return decorations;
}
__delete(variable, fileName, line) {
let decorations = this.get(variable);
if (line !== null) {
decorations = decorations.filter(_ => _.location.fileName !== fileName || (_.location.fileName === fileName && _.location.line !== line));
}
else if (fileName !== null) {
decorations = decorations.filter(_ => _.location.fileName !== fileName);
}
this.entries.set(variable, decorations);
return;
}
delete(variable = null, fileName = null, line = null) {
if (variable !== null) {
return this.__delete(variable, fileName, line);
}
const IT = this.entries.entries();
let tmp = IT.next();
while (tmp.done === false) {
const varName = tmp.value[0];
this.__delete(varName, fileName, line);
tmp = IT.next();
}
}
// not sure it should be here ><
getColor(match, fileName, line) {
let color = null;
const varName = match[1] || match[2];
let variables = [].concat(this.get(varName, fileName, line));
if (variables.length === 0) {
variables = [].concat(this.get(varName));
}
if (variables.length !== 0) {
const variable = variables.pop();
color = new color_1.default(varName, match.index, variable.color.rgb, variable.color.alpha);
}
return color;
}
addEntry(key, value) {
const _value = Array.isArray(value) ? value : [value];
if (this.entries.has(key)) {
const decorations = this.entries.get(key);
this.entries.set(key, decorations.concat(_value));
}
else {
this.entries.set(key, _value);
}
}
// public addEntries(entries: ExtractedDeclarationPlus[]) {
// entries.forEach(({
// varName,
// color,
// content,
// fileName,
// line
// }) => {
// const entry = this.get(varName, fileName, line);
// // color = color || this.getColor(content, fileName, line);
// if (entry.length !== 0) {
// entry[0].update(<Color>color);
// } else {
// const variable = new Variable(varName, <Color>color, {
// fileName,
// line
// });
// this.addEntry(varName, variable);
// }
// });
// }
get count() {
return this.entries.size;
}
// need to create a proxy (?) to always return the same variable.
findDeclaration(variable, file, line) {
return this.findClosestDeclaration(variable, file, line);
}
// need to create a proxy (?) to always return the same variable.
findClosestDeclaration(variable, file, line) {
let decorations = this.get(variable, file);
if (decorations.length === 0) {
decorations = this.get(variable);
}
if (decorations.length === 0) {
this.delete(variable);
}
decorations = this.filterDecorations(decorations, file);
if (line) {
decorations = decorations.filter(decoration => decoration.location.line === line);
}
else {
decorations = decorations.sort((a, b) => a.location.line - b.location.line);
}
const _closest = decorations[decorations.length - 1];
let closest = decorations.pop();
while (closest && closest.color === undefined) {
closest = decorations.pop();
}
return closest || _closest;
}
filterDecorations(decorations, dir) {
const folder = path_1.dirname(dir);
const r = new RegExp(`^${encodeURI(folder)}`);
const decorationsFound = decorations.filter((deco) => r.test(encodeURI(deco.location.fileName)));
if (decorationsFound.length !== 0 || folder === dir) {
return decorationsFound;
}
return this.filterDecorations(decorations, folder);
}
}
exports.default = VariablesStore;
//# sourceMappingURL=variable-store.js.map

View File

@@ -0,0 +1,28 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class Variable {
constructor(name, color, location, type) {
this.name = name;
this.color = color;
this.location = location;
this.type = type;
}
/**
* Generate the color string rgb representation
* example :
* #fff => rgb(255, 255, 255)
* rgba(1, 34, 12, .1) => rgb(1, 34, 12)
*
* @returns {string}
* @public
* @memberOf Color
*/
toRgbString() {
return this.color.toRgbString();
}
update(color) {
this.color = color;
}
}
exports.default = Variable;
//# sourceMappingURL=variable.js.map

View File

@@ -0,0 +1,100 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const color_util_1 = require("../util/color-util");
const extractor_mixin_1 = require("../extractor-mixin");
class VariablesExtractor extends extractor_mixin_1.Extractor {
async extractVariables(fileName, fileLines) {
const colors = await Promise.all(this.enabledStrategies
.map(strategy => strategy
.extractVariables(fileName, fileLines)));
return color_util_1.flattenLineExtractionsFlatten(colors); // should regroup per lines?
}
deleteVariableInLine(fileName, line) {
this.enabledStrategies.forEach(strategy => strategy.deleteVariable(fileName, line));
}
async extractDeclarations(fileName, fileLines) {
return Promise.all(this.enabledStrategies.map(strategy => strategy.extractDeclarations(fileName, fileLines)));
}
getVariablesCount() {
return this.enabledStrategies.reduce((cv, strategy) => cv + strategy.variablesCount(), 0);
}
findVariable(variable) {
return this.get(variable.type).getVariableValue(variable);
}
removeVariablesDeclarations(fileName) {
this.enabledStrategies.forEach(strategy => strategy.deleteVariable(fileName));
}
}
const instance = new VariablesExtractor();
exports.default = instance;
// WARNINGS/Questions
// allow space between var name and ':' ?
// css
//
// is --bar--foo valid?
// Less
//
// This is valid
// @fnord: "I am fnord.";
// @var: "fnord";
// content: @@var;
// give => content: "I am fnord.";
// ?? reserved css "at-rules" ??
// should be excluded or not ? (less/linter should generate an error)
// @charset
// @import
// @namespace
// @media
// @supports
// @document
// @page
// @font-face
// @keyframes
// @viewport
// @counter-style
// @font-feature-values
// @swash
// @ornaments
// @annotation
// @stylistic
// @styleset
// @character-variant)
// stylus
//
// valid
//
// var= #111;
// --a= #fff
// -a=#fff
// _a= #fff
// $a= #fff
//
// not valid
//
// 1a= #fff
// in sass order matter
//
// ```css
// $t: #fff
// $a: $t
// $t: #ccc
//
// p
// color: $a
// ```
// here p.color === #fff
// in less order does not matter
//
// ```css
// @t: #fff
// @a: $t
// @t: #ccc
//
// p
// color: @a
// ```
// here p.color === #ccc
// What about stylus, postcss ???
// should i always use the latest declaration in file?
// vcode-colorize only colorize (does not validate code ¯\_(ツ)_/¯)
//# sourceMappingURL=variables-extractor.js.map

View File

@@ -0,0 +1,70 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const variable_decoration_1 = require("./variable-decoration");
const variables_extractor_1 = require("./variables-extractor");
require("./strategies/css-strategy");
require("./strategies/less-strategy");
require("./strategies/sass-strategy");
require("./strategies/stylus-strategy");
const fs = require("fs");
const vscode_1 = require("vscode");
class VariablesManager {
constructor() {
this.statusBar = vscode_1.window.createStatusBarItem(vscode_1.StatusBarAlignment.Right);
}
async getWorkspaceVariables(includePattern = [], excludePattern = []) {
this.statusBar.show();
this.statusBar.text = 'Colorize: $(loading~spin) Searching for color variables...';
try {
const INCLUDE_PATTERN = `{${includePattern.join(',')}}`;
const EXCLUDE_PATTERN = `{${excludePattern.join(',')}}`;
const files = await vscode_1.workspace.findFiles(INCLUDE_PATTERN, EXCLUDE_PATTERN);
await Promise.all(this.extractFilesVariable(files));
const variablesCount = variables_extractor_1.default.getVariablesCount();
this.statusBar.text = `Colorize: ${variablesCount} variables`;
}
catch (error) {
this.statusBar.color = new vscode_1.ThemeColor('errorForeground');
this.statusBar.text = 'Colorize: $(circle-slash) Variables extraction fail';
}
return;
}
textToDocumentLine(text) {
return text.split(/\n/)
.map((text, index) => Object({
'text': text,
'line': index
}));
}
extractFilesVariable(files) {
return files.map(async (file) => {
const text = fs.readFileSync(file.fsPath, 'utf8');
const content = this.textToDocumentLine(text);
return variables_extractor_1.default.extractDeclarations(file.fsPath, content);
});
}
findVariablesDeclarations(fileName, fileLines) {
return variables_extractor_1.default.extractDeclarations(fileName, fileLines);
}
findVariables(fileName, fileLines) {
return variables_extractor_1.default.extractVariables(fileName, fileLines);
}
findVariable(variable) {
return variables_extractor_1.default.findVariable(variable);
}
generateDecoration(variable, line, decorationFn) {
return new variable_decoration_1.default(variable, line, decorationFn);
}
setupVariablesExtractors(extractors) {
variables_extractor_1.default.enableStrategies(extractors);
}
deleteVariableInLine(fileName, line) {
variables_extractor_1.default.deleteVariableInLine(fileName, line);
}
removeVariablesDeclarations(fileName) {
variables_extractor_1.default.removeVariablesDeclarations(fileName);
}
}
const instance = new VariablesManager();
exports.default = instance;
//# sourceMappingURL=variables-manager.js.map

View File

@@ -0,0 +1,217 @@
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode_1 = require("vscode");
const extension_1 = require("./extension");
const color_util_1 = require("./lib/util/color-util");
const variables_manager_1 = require("./lib/variables/variables-manager");
const editor_manager_1 = require("./lib/editor-manager");
const mut_edited_line_1 = require("./lib/util/mut-edited-line");
const array_1 = require("./lib/util/array");
const tasks_runner_1 = require("./lib/tasks-runner");
// eslint-disable-next-line
// @ts-ignore
const taskRuner = new tasks_runner_1.default();
const clearDecoration = (decoration) => decoration.dispose();
function filterPositions(position, deco, diffLine) {
if (position.updated === null) {
deco.get(position.old).forEach(clearDecoration);
return false;
}
if (position.updated === 0 && extension_1.extension.editor.document.lineCount === 1 && extension_1.extension.editor.document.lineAt(0).text === '') {
deco.get(position.old).forEach(clearDecoration);
return false;
}
if (Math.abs(position.old - position.updated) > Math.abs(diffLine)) {
position.updated = position.old + diffLine;
}
return true;
}
function disposeDecorationsForEditedLines(editedLine, context) {
editedLine.map(({ range }) => {
const line = range.start.line;
if (context.deco.has(line)) {
context.deco.get(line).forEach(clearDecoration);
}
});
}
function updatePositionsDeletion(range, positions) {
const rangeLength = range.end.line - range.start.line;
positions.forEach(position => {
if (position.updated === null) {
return;
}
if (position.old > range.start.line && position.old <= range.end.line) {
position.updated = null;
return;
}
if (position.old >= range.end.line) {
position.updated = position.updated - rangeLength;
}
if (position.updated < 0) {
position.updated = 0;
}
});
return positions;
}
function getRemovedLines(editedLine, positions) {
editedLine.reverse();
editedLine.forEach((line) => {
for (let i = line.range.start.line; i <= line.range.end.line; i++) {
// ?
// for (let i = line.range.start.line; i <= context.editor.document.lineCount; i++) {
variables_manager_1.default.deleteVariableInLine(extension_1.extension.editor.document.fileName, i);
}
positions = updatePositionsDeletion(line.range, positions);
});
return editedLine;
}
function getAddedLines(editedLine, positions) {
editedLine = mut_edited_line_1.mutEditedLine(editedLine);
editedLine.forEach((line) => {
positions.forEach(position => {
if (position.updated >= line.range.start.line) {
position.updated = position.updated + 1;
}
});
});
return editedLine;
}
function getEditedLines(editedLine, context, diffLine) {
let positions = Array
.from(context.deco.keys())
.map(position => ({
old: position,
updated: position
}));
if (diffLine < 0) {
editedLine = getRemovedLines(editedLine, positions);
}
else {
editedLine = getAddedLines(editedLine, positions);
}
positions = positions.filter(position => filterPositions(position, context.deco, diffLine));
context.deco = positions.reduce((decorations, position) => {
if (decorations.has(position.updated)) {
const decos = decorations.get(position.updated).concat(context.deco.get(position.old));
decos.forEach(deco => deco.generateRange(position.updated));
return decorations.set(position.updated, decos);
}
const decos = context.deco.get(position.old);
decos.forEach(deco => deco.generateRange(position.updated));
return decorations.set(position.updated, context.deco.get(position.old));
}, new Map());
return editedLine;
}
function getDecorationsToColorize(colors, variables) {
const decorations = extension_1.generateDecorations(colors, variables, new Map());
function filterDuplicated(A, B) {
return A.filter((decoration) => {
const exist = B.findIndex((_) => {
const position = decoration.currentRange.isEqual(_.currentRange);
if (decoration.rgb === null && _.rgb !== null) {
return false;
}
const colors = array_1.equals(decoration.rgb, _.rgb);
return position && colors;
});
return exist === -1;
});
}
extension_1.extension.editor.visibleRanges.forEach(range => {
let i = range.start.line;
for (i; i <= range.end.line + 1; i++) {
if (extension_1.extension.deco.has(i) === true && decorations.has(i) === true) {
// compare and remove duplicate and remove deleted ones
decorations.set(i, filterDuplicated(decorations.get(i), extension_1.extension.deco.get(i)));
}
if (extension_1.extension.deco.has(i) && !decorations.has(i)) {
// dispose decorations
extension_1.extension.deco.get(i).forEach(clearDecoration);
}
}
});
cleanDecorationMap(decorations);
return decorations;
}
function getCurrentRangeText() {
const text = extension_1.extension.editor.document.getText();
const fileLines = color_util_1.default.textToFileLines(text);
const lines = [];
extension_1.extension.editor.visibleRanges.forEach((range) => {
let i = range.start.line;
for (i; i <= range.end.line + 1; i++) {
if (fileLines[i] && fileLines[i].line !== null) {
lines.push(fileLines[i]);
}
}
});
return lines;
}
// Need to regenerate variables decorations when base as changed
function* handleVisibleRangeEvent() {
// trigger on ctrl + z ????
// yield new Promise(resolve => setTimeout(resolve, 50));
const text = extension_1.extension.editor.document.getText();
const fileLines = color_util_1.default.textToFileLines(text);
const lines = getCurrentRangeText();
yield variables_manager_1.default.findVariablesDeclarations(extension_1.extension.editor.document.fileName, fileLines);
const variables = yield variables_manager_1.default.findVariables(extension_1.extension.editor.document.fileName, lines);
const colors = yield color_util_1.default.findColors(lines);
const decorations = getDecorationsToColorize(colors, variables);
editor_manager_1.default.decorate(extension_1.extension.editor, decorations, extension_1.extension.currentSelection);
extension_1.updateContextDecorations(decorations, extension_1.extension);
extension_1.removeDuplicateDecorations(extension_1.extension);
}
function* updateDecorations() {
yield new Promise(resolve => setTimeout(resolve, 50));
const fileName = extension_1.extension.editor.document.fileName;
const fileLines = color_util_1.default.textToFileLines(extension_1.extension.editor.document.getText());
const lines = getCurrentRangeText();
variables_manager_1.default.removeVariablesDeclarations(extension_1.extension.editor.document.fileName);
cleanDecorationMap(extension_1.extension.deco);
yield variables_manager_1.default.findVariablesDeclarations(fileName, fileLines);
const variables = yield variables_manager_1.default.findVariables(fileName, lines);
const colors = yield color_util_1.default.findColors(lines);
const decorations = getDecorationsToColorize(colors, variables);
// removeDuplicateDecorations(decorations);
editor_manager_1.default.decorate(extension_1.extension.editor, decorations, extension_1.extension.currentSelection);
extension_1.updateContextDecorations(decorations, extension_1.extension);
extension_1.removeDuplicateDecorations(extension_1.extension);
}
// Return new map?
function cleanDecorationMap(decorations) {
const it = decorations.entries();
let tmp = it.next();
while (!tmp.done) {
const line = tmp.value[0];
const deco = tmp.value[1];
decorations.set(line, deco.filter(decoration => !decoration.disposed));
tmp = it.next();
}
}
function textDocumentUpdated(event) {
if (event.contentChanges.length === 0) {
return;
}
if (extension_1.extension.editor && event.document.fileName === extension_1.extension.editor.document.fileName) {
extension_1.extension.editor = vscode_1.window.activeTextEditor;
let editedLine = event.contentChanges.map(_ => _);
const diffLine = extension_1.extension.editor.document.lineCount - extension_1.extension.nbLine;
if (diffLine !== 0) {
editedLine = getEditedLines(editedLine, extension_1.extension, diffLine);
extension_1.extension.nbLine = extension_1.extension.editor.document.lineCount;
}
disposeDecorationsForEditedLines(editedLine, extension_1.extension);
taskRuner.run(updateDecorations);
}
}
function setupEventListeners(context) {
// window.onDidChangeTextEditorSelection((event) => q.push((cb) => handleTextSelectionChange(event, cb)), null, context.subscriptions);
vscode_1.workspace.onDidChangeTextDocument(textDocumentUpdated, null, context.subscriptions);
vscode_1.window.onDidChangeTextEditorVisibleRanges(() => taskRuner.run(handleVisibleRangeEvent), null, context.subscriptions);
// window.onDidChangeTextEditorVisibleRanges(handleVisibleRangeEvent, null, context.subscriptions);
}
exports.default = { setupEventListeners };
//# sourceMappingURL=listeners.js.map

View File

@@ -0,0 +1,213 @@
{
"name": "vscode-colorize",
"displayName": "colorize",
"description": "A vscode extension to help visualize css colors in files.",
"version": "0.11.1",
"publisher": "kamikillerto",
"license": "Apache-2.0",
"icon": "assets/logo.png",
"engines": {
"vscode": "^1.54.0"
},
"categories": [
"Other"
],
"keywords": [
"color",
"css",
"hexa",
"hsl",
"rgb",
"preprocessor"
],
"repository": {
"type": "git",
"url": "https://github.com/kamikillerto/vscode-colorize.git"
},
"bugs": {
"url": "https://github.com/kamikillerto/vscode-colorize/issues"
},
"homepage": "https://github.com/kamikillerto/vscode-colorize/blob/master/README.MD",
"galleryBanner": {
"theme": "light"
},
"activationEvents": [
"*"
],
"main": "./out/src/extension",
"contributes": {
"configuration": {
"title": "Colorize",
"properties": {
"colorize.languages": {
"default": [
"css",
"sass",
"scss",
"less",
"postcss",
"sss",
"stylus",
"xml",
"svg"
],
"title": "Colorize files with these languages",
"type": "array",
"markdownDescription": "Configure a list of languages that should be colorized. A list of languages can be find at https://code.visualstudio.com/docs/languages/identifiers. You can learn about languages at https://code.visualstudio.com/docs/languages/overview."
},
"colorize.include": {
"type": "array",
"markdownDescription": "Configure glob patterns for including files and folders. By default Colorize is enable for files matching one the languages defined in the `colorize.languages` config, with this config you can enable colorize for other files or folders. Read more about glob patterns [here](https://code.visualstudio.com/docs/editor/codebasics#_advanced-search-options).",
"default": [
"**/*.css",
"**/*.scss",
"**/*.sass",
"**/*.less",
"**/*.styl"
],
"scope": 3,
"additionalProperties": {
"anyOf": [
{
"type": "array",
"properties": {
"when": {
"type": "string",
"pattern": "\\w*\\$\\(basename\\)\\w*",
"default": "$(basename).ext",
"description": "Additional check on the siblings of a matching file. Use $(basename) as variable for the matching file name."
}
}
}
]
}
},
"colorize.exclude": {
"type": "array",
"markdownDescription": "Configure glob patterns for excluding files and folders. Colorize will not colorized colors in these files and folders and it'll also not search for variables inside. Read more about glob patterns [here](https://code.visualstudio.com/docs/editor/codebasics#_advanced-search-options).",
"default": [
"**/.git",
"**/.svn",
"**/.hg",
"**/CVS",
"**/.DS_Store",
"**/.git",
"**/node_modules",
"**/bower_components",
"**/tmp",
"**/dist",
"**/tests"
],
"scope": 3,
"additionalProperties": {
"anyOf": [
{
"type": "array",
"properties": {
"when": {
"type": "string",
"pattern": "\\w*\\$\\(basename\\)\\w*",
"default": "$(basename).ext",
"description": "Additional check on the siblings of a matching file. Use $(basename) as variable for the matching file name."
}
}
}
]
}
},
"colorize.hide_current_line_decorations": {
"title": "Hide current line decorations",
"default": true,
"type": "boolean",
"markdownDescription": "Hide colors for the current line. Set to `false` to turn it off"
},
"colorize.colorized_variables": {
"$schema": "http://json-schema.org/draft-07/schema#",
"default": [
"CSS"
],
"items": {
"enum": [
"CSS",
"SASS",
"LESS",
"STYLUS"
],
"description": "You should enter a valid extractor",
"uniqueItems": true
},
"title": "Extract these type of variables",
"type": "array",
"markdownDescription": "You can specified the type of variables that should be colorized by the extension."
},
"colorize.decoration_type": {
"title": "Type of decoration",
"type": "string",
"enum": [
"background",
"underline"
],
"default": "background"
},
"colorize.colorized_colors": {
"$schema": "http://json-schema.org/draft-07/schema#",
"default": [
"BROWSERS_COLORS",
"HEXA",
"RGB",
"HSL"
],
"items": {
"enum": [
"BROWSERS_COLORS",
"HEXA",
"RGB",
"HSL",
"ARGB"
],
"description": "You should enter a valid extractor",
"uniqueItems": true
},
"title": "Colorize these type of color",
"type": "array",
"markdownDescription": "You can specified the type of color that should be colorized by the extension.\nAvailable colors are:\n* `HEXA`: for hexadecimal colors: `#RGB`, `#RGBA`, `#RRGGBB`, `#RRGGBBAA`, `0xRGB`, `0xRGBA`, `0xRRGGBB` or `0xRRGGBBAA`\n* `ARGB`: for argb colors: `#RGB`, `#ARGB`, `#RRGGBB` or `#AARRGGBB`\n* `RGB`: for rgb colors: `rgb(r,g,b)` or `rgba(r,g,b,a)`\n* `HSL`: for HSL colors: `hsl(h,s,l)` or `hsla(h,s,l,a)`\n* `BROWSERS_COLORS`: for native browser's colors like `white`, `red`, `blue`..."
},
"colorize.enable_search_variables": {
"title": "Enable the search for variables at opening time",
"default": true,
"type": "boolean",
"markdownDescription": "When vscode starts, Colorize fetch all files targeted by the settings `colorize.include` and `colorize.languages` but not the ones targeted by the setting `colorize.exclude`. When the fetch is done, colorize open and parse all files searching for variables. That way variables will be colorized in every files. _⚠ this setting can slown down your editor a little at opening time, read this [issue](https://github.com/KamiKillertO/vscode-colorize/issues/174) to learn more about it._"
}
}
}
},
"scripts": {
"vscode:prepublish": "tsc -p ./",
"compile": "tsc -watch -p ./",
"lint": "eslint .",
"test": "npm run vscode:prepublish; node ./out/test/runTest.js"
},
"devDependencies": {
"@types/chai": "^4.2.17",
"@types/mocha": "^8.2.2",
"@types/node": "^12.0.0",
"@types/vscode": "^1.54.0",
"@typescript-eslint/eslint-plugin": "^4.22.0",
"@typescript-eslint/parser": "^4.22.0",
"chai": "^4.3.4",
"eslint": "^7.25.0",
"mocha": "^8.3.2",
"typescript": "^3.9.3",
"vscode-test": "^1.5.2"
},
"dependencies": {
"glob-to-regexp": "^0.4.1"
},
"__metadata": {
"id": "445ba381-f232-4150-9056-d790bd76d698",
"publisherId": "d4ae7698-aa41-4455-92f8-cbb52b3d5004",
"publisherDisplayName": "kamikillerto",
"isPreReleaseVersion": false,
"installedTimestamp": 1641229847861
}
}