├── .appcast.xml
├── .babelrc
├── .gitignore
├── .vscode
└── settings.json
├── LICENSE
├── README.md
├── art
├── example.png
└── icon.sketch
├── assets
└── icon.png
├── package-lock.json
├── package.json
└── src
├── commands.js
├── lib
└── util.js
└── manifest.json
/.appcast.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | -
5 |
6 |
7 | -
8 |
9 |
10 | -
11 |
12 |
13 | -
14 |
15 |
16 | -
17 |
18 |
19 | -
20 |
21 |
22 | -
23 |
24 |
25 | -
26 |
27 |
28 | -
29 |
30 |
31 | -
32 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "plugins": ["@babel/plugin-proposal-object-rest-spread"]
3 | }
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | _sandbox
2 |
3 | # Sketch Runner no longer requires this in the repo
4 | *.sketchplugin
5 |
6 | # npm
7 | node_modules
8 | .npm
9 | npm-debug.log
10 |
11 | # mac
12 | .DS_Store
13 |
14 | # WebStorm
15 | .idea
16 |
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "search.exclude": {
3 | "**/node_modules": true,
4 | "*.sketchplugin": true
5 | }
6 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | # Contrast plugin for Sketch
4 |
5 | This plugin generates a pass/fail type contrast report (currently AA only) for an artboard or a page:
6 |
7 |
8 |
9 | # Installation
10 |
11 | * [Download the latest release](https://github.com/romannurik/Sketch-Contrast/releases/latest) and double-click the `.sketchplugin` file to install.
12 | * Sketch Runner support is coming soon!
13 |
14 | # Build instructions
15 |
16 | _This plugin was created using `skpm`. For a detailed explanation on how things work, checkout the [skpm Readme](https://github.com/skpm/skpm/blob/master/README.md)._
17 |
--------------------------------------------------------------------------------
/art/example.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/romannurik/Sketch-Contrast/31efd165240d20c5fd62fab27780b2dccc04cd11/art/example.png
--------------------------------------------------------------------------------
/art/icon.sketch:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/romannurik/Sketch-Contrast/31efd165240d20c5fd62fab27780b2dccc04cd11/art/icon.sketch
--------------------------------------------------------------------------------
/assets/icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/romannurik/Sketch-Contrast/31efd165240d20c5fd62fab27780b2dccc04cd11/assets/icon.png
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "sketch-contrast",
3 | "description": "A Sketch plugin to show a pass/fail type contrast report.",
4 | "version": "0.1.10",
5 | "engines": {
6 | "sketch": ">=49.0.0"
7 | },
8 | "skpm": {
9 | "name": "Contrast",
10 | "manifest": "src/manifest.json",
11 | "main": "Contrast.sketchplugin",
12 | "assets": [
13 | "assets/**/*"
14 | ]
15 | },
16 | "repository": {
17 | "type": "git",
18 | "url": "https://github.com/romannurik/Sketch-Contrast.git"
19 | },
20 | "license": "Apache-2.0",
21 | "bugs": {
22 | "url": "https://github.com/romannurik/Sketch-Contrast/issues"
23 | },
24 | "homepage": "https://github.com/romannurik/Sketch-Contrast#readme",
25 | "scripts": {
26 | "build": "skpm-build",
27 | "start": "skpm-build --watch",
28 | "postinstall": "npm run build && skpm-link"
29 | },
30 | "devDependencies": {
31 | "@babel/plugin-proposal-object-rest-spread": "^7.0.0-beta.44",
32 | "@skpm/builder": "^0.5.9"
33 | },
34 | "author": "Roman Nurik ",
35 | "dependencies": {
36 | "@skpm/fs": "^0.1.2",
37 | "@skpm/path": "^0.1.0",
38 | "mocha-js-delegate": "^0.1.1"
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/commands.js:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Google Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | import UI from 'sketch/ui';
18 | import * as util from './lib/util';
19 |
20 |
21 | const META_GROUP_NAME = '___CONTRAST___';
22 | const TEXT_LAYER_PREDICATE = NSPredicate.predicateWithFormat('className == %@', 'MSTextLayer');
23 |
24 |
25 | const Colors = {
26 | PASS: util.svgColorToMSColor('rgba(0, 178, 0, .4)'),
27 | FAIL: util.svgColorToMSColor('rgba(255, 0, 0, .4)'),
28 | UNKNOWN: util.svgColorToMSColor('rgba(255, 213, 79, .4)'),
29 | };
30 |
31 |
32 | const Mode = {
33 | IMAGE: 0,
34 | INLINE: 1,
35 | };
36 |
37 |
38 | export function onCheckCurrentArtboard(context) {
39 | if (!context.selection.length) {
40 | UI.message('Select a layer in an artboard');
41 | return;
42 | }
43 |
44 | let artboard = context.selection[0];
45 | while (artboard && !(artboard instanceof MSArtboardGroup)) {
46 | artboard = artboard.parentGroup();
47 | }
48 |
49 | if (!artboard) {
50 | UI.message('Select a layer in an artboard');
51 | return;
52 | }
53 |
54 | let {path} = createContrastReport(context, artboard, {mode: Mode.IMAGE});
55 | NSWorkspace.sharedWorkspace().openFile(path);
56 | }
57 |
58 |
59 | export function onCheckAllArtboards(context) {
60 | let page = context.document.currentPage();
61 | if (removeInlineContrastReports(page)) {
62 | return;
63 | }
64 |
65 | Array.from(page.layers()).filter(l => l instanceof MSArtboardGroup).forEach(a => {
66 | createContrastReport(context, a, {mode: Mode.INLINE});
67 | });
68 | }
69 |
70 |
71 | /**
72 | * Removes inline contrast reports created by the INLINE mode under the given parent
73 | * (document, page, or artboard). Returns true if anything was removed.
74 | */
75 | function removeInlineContrastReports(parent) {
76 | let contrastMetaGroups = util.getAllLayersMatchingPredicate(
77 | parent,
78 | NSPredicate.predicateWithFormat('name == %@', META_GROUP_NAME));
79 | if (contrastMetaGroups.length) {
80 | contrastMetaGroups.forEach(g => g.removeFromParent());
81 | return true;
82 | }
83 |
84 | return false;
85 | }
86 |
87 |
88 | /**
89 | * Creates a contrast report for the given artboard. Mode options are IMAGE,
90 | * which produces a PNG file report, or INLINE which draws the report in the artboard.
91 | */
92 | function createContrastReport(context, artboard, {mode = Mode.IMAGE} = {}) {
93 | let artboardCopy = artboard.copy();
94 | context.document.currentPage().addLayer(artboardCopy);
95 |
96 | let visibleTextLayerInfos = findVisibleTextLayerInfos(artboardCopy);
97 | visibleTextLayerInfos.forEach(({layer}) => layer.setIsVisible(false));
98 | let metaGroup = MSLayerGroup.new();
99 | metaGroup.setName(META_GROUP_NAME);
100 | if (mode == Mode.IMAGE) {
101 | artboardCopy.addLayer(metaGroup);
102 | } else {
103 | artboard.addLayer(metaGroup);
104 | }
105 | let {image} = util.getArtboardImage(context.document, artboardCopy);
106 | let bitmapImageRep = NSBitmapImageRep.imageRepWithData(image.TIFFRepresentation());
107 | for (let {layer, opacity, rectangle} of visibleTextLayerInfos) {
108 | let rating = getTypeContrastRating(
109 | layer, opacity, rectangle, bitmapImageRep);
110 | renderContrastReportOverlay(metaGroup, rectangle, rating);
111 | }
112 | visibleTextLayerInfos.forEach(({layer}) => layer.setIsVisible(true));
113 | let returnValue = {};
114 | if (mode == Mode.IMAGE) {
115 | returnValue = util.getArtboardImage(context.document, artboardCopy);
116 | }
117 |
118 | artboardCopy.removeFromParent();
119 | return returnValue;
120 | }
121 |
122 |
123 | /**
124 | * Renders a contrast report overlay at the given coordinates (pass/fail, etc)
125 | */
126 | function renderContrastReportOverlay(metaGroup, {x, y, w, h}, {contrastRatio, note, status}) {
127 | let overlayText = note;
128 | let fillLayer = MSShapeGroup.shapeWithRect(NSMakeRect(x, y, w, h));
129 | let fill = fillLayer.style().addStylePartOfType(util.StylePartType.FILL);
130 | switch (status) {
131 | case 'pass':
132 | fill.color = Colors.PASS;
133 | break;
134 | case 'fail':
135 | fill.color = Colors.FAIL;
136 | overlayText = formatContrastRatio(contrastRatio);
137 | break;
138 | case 'unknown':
139 | case 'mixed':
140 | fill.color = Colors.UNKNOWN;
141 | break;
142 | }
143 | metaGroup.addLayer(fillLayer);
144 | if (overlayText) {
145 | let overlayTextLayer = MSTextLayer.new();
146 | overlayTextLayer.setStringValue(overlayText);
147 | if (w < 100) {
148 | let delta = (100 - w);
149 | x -= delta / 2;
150 | w = 100;
151 | }
152 | overlayTextLayer.frame = MSRect.rectWithRect(NSMakeRect(x, y, w, h));
153 | overlayTextLayer.setTextBehaviour(2); // fixed
154 | overlayTextLayer.setTextAlignment(2); // center
155 | overlayTextLayer.setVerticalAlignment(1); // center
156 | overlayTextLayer.setFont(NSFont.boldSystemFontOfSize(10));
157 | overlayTextLayer.setTextColor(util.svgColorToMSColor('#fff'));
158 | let shadow = overlayTextLayer.style().addStylePartOfType(util.StylePartType.SHADOW);
159 | shadow.offsetX = 0;
160 | shadow.offsetY = 1;
161 | shadow.blurRadius = 1;
162 | shadow.color = util.svgColorToMSColor('rgba(0,0,0,0.5)');
163 | metaGroup.addLayer(overlayTextLayer);
164 | }
165 | }
166 |
167 |
168 | /**
169 | * Takes a number like 5.561236 and formats it as a contrast ratio like 5.57:1
170 | */
171 | function formatContrastRatio(contrastRatio) {
172 | return isNaN(contrastRatio) ? 'NA' : contrastRatio.toFixed(2) + ':1';
173 | }
174 |
175 |
176 | /**
177 | * Computes the AA contrast rating (pass/fail) for the given text layer, at the given
178 | * opacity, using the background determined by the given rectangular cutout of the given
179 | * NSBitmapImageRep.
180 | */
181 | function getTypeContrastRating(textLayer, opacity, {x, y, w, h}, bitmapImageRep) {
182 | let samplePoints = [
183 | // TODO: adaptive sampling?
184 | [x, y],
185 | // as of last testing, runtime diff. sampling 4 vs. 1 points only took ~5% longer
186 | [x + w - 1, y],
187 | [x, y + h - 1],
188 | [x + h - 1, y + h - 1],
189 | ];
190 |
191 | let textStyleAttr = textLayer.style().textStyle().attributes();
192 | let textMSColor = textStyleAttr.MSAttributedStringColorAttribute; // actually an MSImmutableColor
193 | if (!textMSColor) {
194 | let names = [];
195 | let parent = textLayer;
196 | while (parent) {
197 | names.unshift(parent.name());
198 | parent = parent.parentGroup();
199 | }
200 | log(`Can't get text color for text layer ${names.join(' > ')}`);
201 | return {status: 'unknown', contrastRatio: 'NA'};
202 | }
203 |
204 | // check for tints (fill styles on parent layers that override the text color)
205 | let parent = textLayer.parentGroup();
206 | while (parent) {
207 | let fills = Array.from(parent.style().stylePartsOfType(util.StylePartType.FILL));
208 | if (fills.length) {
209 | for (let fill of fills) {
210 | textMSColor = fill.color();
211 | }
212 | }
213 | parent = parent.parentGroup();
214 | }
215 |
216 | let textColor = {
217 | r: Math.round(255 * textMSColor.red()),
218 | g: Math.round(255 * textMSColor.green()),
219 | b: Math.round(255 * textMSColor.blue()),
220 | a: Math.round(255 * textMSColor.alpha()),
221 | };
222 |
223 | let pointSize = textStyleAttr.NSFont.pointSize() / 1.333333333; // CSS px -> pt
224 | let isBold = /(medium|bold|black)/i.test(textStyleAttr.NSFont.fontName());
225 | let largeText = pointSize >= 18 || (isBold && pointSize >= 14);
226 | let passingContrastForLayer = largeText ? 3 : 4.5;
227 |
228 | let stats = {fail: 0, pass: 0, minCR: Infinity, maxCR: 0};
229 |
230 | for (let [x_, y_] of samplePoints) {
231 | let bgNSColor = bitmapImageRep.colorAtX_y_(x_, y_);
232 | if (!bgNSColor) {
233 | // likely this sample point is out of bounds
234 | continue;
235 | }
236 |
237 | let bgColor = {
238 | r: Math.round(255 * bgNSColor.redComponent()),
239 | g: Math.round(255 * bgNSColor.greenComponent()),
240 | b: Math.round(255 * bgNSColor.blueComponent()),
241 | a: Math.round(255 * bgNSColor.alphaComponent()),
242 | };
243 |
244 | let blendedTextColor = util.mixColors(bgColor, textColor,
245 | (textColor.a * opacity) / 255 * 100);
246 |
247 | let lum1 = util.srgbLuminance(blendedTextColor);
248 | let lum2 = util.srgbLuminance(bgColor);
249 | let contrastRatio = (Math.max(lum1, lum2) + 0.05) / (Math.min(lum1, lum2) + 0.05);
250 | stats.minCR = Math.min(stats.minCR, contrastRatio);
251 | stats.maxCR = Math.max(stats.maxCR, contrastRatio);
252 | if (contrastRatio < passingContrastForLayer) {
253 | ++stats.fail;
254 | } else {
255 | ++stats.pass;
256 | }
257 | }
258 |
259 | if (stats.fail > 0 && stats.pass > 0) {
260 | return {
261 | status: 'mixed',
262 | contrastRatio: stats.minCR,
263 | note: formatContrastRatio(stats.minCR) + ' - ' + formatContrastRatio(stats.maxCR),
264 | };
265 | } else if (stats.fail > 0) {
266 | return { status: 'fail', contrastRatio: stats.minCR };
267 | } else if (stats.pass > 0) {
268 | return { status: 'pass', contrastRatio: stats.minCR };
269 | } else {
270 | return { status: 'unknown', contrastRatio: 0 };
271 | }
272 | }
273 |
274 |
275 | /**
276 | * Deep-search for visible MSTextLayers in the given parent layer, returning an array
277 | * containing the layer, its frame rectangle, and effective opacity.
278 | *
279 | * Has side effects! Will detach symbols.
280 | */
281 | function findVisibleTextLayerInfos(parent) {
282 | let visibleTextLayers = util.getAllLayersMatchingPredicate(
283 | parent,
284 | TEXT_LAYER_PREDICATE);
285 |
286 | visibleTextLayers = visibleTextLayers.filter(layer => {
287 | while (layer && layer !== parent) {
288 | if (!layer.isVisible()) {
289 | return false;
290 | }
291 | layer = layer.parentGroup();
292 | }
293 |
294 | return true;
295 | });
296 |
297 | let visibleTextLayerInfos = visibleTextLayers.map(layer => {
298 | let frame = layer.frame();
299 | let rectangle = { x: frame.x(), y: frame.y(), w: frame.width(), h: frame.height() };
300 | let parent = layer.parentGroup();
301 | let opacity = 1;
302 | while (parent && !(parent instanceof MSArtboardGroup || parent instanceof MSSymbolMaster)) {
303 | rectangle.x += parent.frame().x();
304 | rectangle.y += parent.frame().y();
305 | opacity *= parent.style().contextSettings().opacity();
306 | parent = parent.parentGroup();
307 | }
308 |
309 | return {
310 | layer,
311 | opacity,
312 | rectangle
313 | };
314 | });
315 |
316 | let symbolInstances = util.getAllLayersMatchingPredicate(
317 | parent,
318 | NSPredicate.predicateWithFormat('className == %@', 'MSSymbolInstance'))
319 | .filter(symbolInstance => doesSymbolInstanceHaveTextLayers(symbolInstance));
320 | for (let symbolInstance of symbolInstances) {
321 | // symbol instance has text layers; detach it to a group to allow hiding them
322 | // before doing that, see if the symbol includes its background in instances
323 | let master = symbolInstance.symbolMaster();
324 | let frame = symbolInstance.frame();
325 | let bgColor = (master && master.includeBackgroundColorInInstance())
326 | ? master.backgroundColor() : null;
327 | let detachedSymbol;
328 | if (symbolInstance.detachStylesAndReplaceWithGroupRecursively) {
329 | let map = symbolInstance.detachStylesAndReplaceWithGroupRecursively();
330 | detachedSymbol = map.objectForKey(symbolInstance.immutableModelObject());
331 | } else {
332 | detachedSymbol = symbolInstance.detachByReplacingWithGroup();
333 | }
334 |
335 | if (detachedSymbol) {
336 | visibleTextLayerInfos = [
337 | ...visibleTextLayerInfos,
338 | ...findVisibleTextLayerInfos(detachedSymbol)
339 | ];
340 | }
341 | if (bgColor) {
342 | let bgLayer = MSShapeGroup.shapeWithRect(
343 | NSMakeRect(frame.x(), frame.y(), frame.width(), frame.height()));
344 | let fill = bgLayer.style().addStylePartOfType(util.StylePartType.FILL);
345 | fill.color = bgColor;
346 | detachedSymbol.parentGroup().insertLayer_beforeLayer_(bgLayer, detachedSymbol);
347 | }
348 | }
349 |
350 | return visibleTextLayerInfos;
351 | }
352 |
353 |
354 | /**
355 | * Returns true if the given MSSymbolInstance contains text layers
356 | */
357 | function doesSymbolInstanceHaveTextLayers(symbolInstance) {
358 | if (!symbolInstance.symbolMaster()) {
359 | return true; // just in case
360 | }
361 |
362 | // TODO: cache true/false for a given master
363 | if (util.getAllLayersMatchingPredicate(
364 | symbolInstance.symbolMaster(),
365 | TEXT_LAYER_PREDICATE).length) {
366 | return true;
367 | }
368 |
369 | // check for symbol instance children that have text layers
370 | let symbolInstances = util.getAllLayersMatchingPredicate(
371 | symbolInstance.symbolMaster(),
372 | NSPredicate.predicateWithFormat('className == %@', 'MSSymbolInstance'));
373 | for (let symbolInstance of symbolInstances) {
374 | if (doesSymbolInstanceHaveTextLayers(symbolInstance)) {
375 | return true;
376 | }
377 | }
378 |
379 | return false;
380 | }
381 |
--------------------------------------------------------------------------------
/src/lib/util.js:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Google Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 |
18 | export const StylePartType = {
19 | FILL: 0,
20 | // BORDER: 1 ?
21 | SHADOW: 2,
22 | INNER_SHADOW: 3,
23 | };
24 |
25 |
26 | /**
27 | * Returns the first layer matching the given NSPredicate
28 | *
29 | * @param {MSDocument|MSLayerGroup} parent The document or layer group to search.
30 | * @param {NSPredicate} predicate Search predicate
31 | */
32 | export function getAllLayersMatchingPredicate(parent, predicate) {
33 | if (parent instanceof MSDocument) {
34 | // MSDocument
35 | return parent.pages().reduce(
36 | (acc, page) => acc.concat(getAllLayersMatchingPredicate(page, predicate)),
37 | []);
38 | }
39 |
40 | // assume MSLayerGroup
41 | return Array.from(parent.children().filteredArrayUsingPredicate(predicate));
42 | }
43 |
44 |
45 | /**
46 | * Calculates the luminance of the given RGB color.
47 | */
48 | export function srgbLuminance({r, g, b}) {
49 | // from tinycolor
50 | // https://github.com/bgrins/TinyColor/blob/master/tinycolor.js#L75
51 | // http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef
52 | let RsRGB, GsRGB, BsRGB, R, G, B;
53 | RsRGB = r / 255;
54 | GsRGB = g / 255;
55 | BsRGB = b / 255;
56 |
57 | if (RsRGB <= 0.03928) {R = RsRGB / 12.92;} else {R = Math.pow(((RsRGB + 0.055) / 1.055), 2.4);}
58 | if (GsRGB <= 0.03928) {G = GsRGB / 12.92;} else {G = Math.pow(((GsRGB + 0.055) / 1.055), 2.4);}
59 | if (BsRGB <= 0.03928) {B = BsRGB / 12.92;} else {B = Math.pow(((BsRGB + 0.055) / 1.055), 2.4);}
60 | return (0.2126 * R) + (0.7152 * G) + (0.0722 * B);
61 | }
62 |
63 |
64 | /**
65 | * Mixes the given colors (RGB dicts) at the given amount (0 to 100).
66 | */
67 | export function mixColors(c1, c2, amount) {
68 | // from tinycolor
69 | // https://github.com/bgrins/TinyColor/blob/master/tinycolor.js#L701
70 | amount = (amount === 0) ? 0 : (amount || 50);
71 |
72 | let p = amount / 100;
73 |
74 | return {
75 | r: ((c2.r - c1.r) * p) + c1.r,
76 | g: ((c2.g - c1.g) * p) + c1.g,
77 | b: ((c2.b - c1.b) * p) + c1.b,
78 | // a: ((c2.a - c1.a) * p) + c1.a
79 | };
80 | }
81 |
82 |
83 | /**
84 | * Returns an MSColor for the given SVG color (e.g. #fff or rgba(0,0,0,.5))
85 | */
86 | export function svgColorToMSColor(svgColor) {
87 | return MSColor.alloc().initWithImmutableObject_(MSImmutableColor.colorWithSVGString(svgColor));
88 | }
89 |
90 |
91 | /**
92 | * Saves the given artboard to a temporary PNG file and returns the path and an NSImage
93 | */
94 | export function getArtboardImage(document, artboard) {
95 | let tempPath = NSTemporaryDirectory().stringByAppendingPathComponent(
96 | NSUUID.UUID().UUIDString() + '.png');
97 | // let frame = artboard.frame();
98 | // let rect = NSMakeRect(frame.origin.x, frame.origin.y, frame.size.width, frame.size.height);
99 | let ancestry;
100 | if (artboard.ancestry) {
101 | // sketch 66
102 | ancestry = artboard.ancestry();
103 | } else {
104 | ancestry = MSImmutableLayerAncestry.ancestryWithMSLayer_(artboard);
105 | }
106 | let exportRequest = MSExportRequest.exportRequestsFromLayerAncestry_(
107 | ancestry,
108 | // rect // we pass this to avoid trimming
109 | ).firstObject();
110 | exportRequest.format = 'png';
111 | exportRequest.scale = 1;
112 | document.saveArtboardOrSlice_toFile_(exportRequest, tempPath);
113 | return {
114 | path: tempPath,
115 | image: NSImage.alloc().initWithContentsOfFile(tempPath)
116 | };
117 | }
118 |
119 |
120 | /**
121 | * Decorator-style function that returns a new function that logs the duration of each
122 | * call to it.
123 | */
124 | export function profiled(fn) {
125 | return function () {
126 | let start = Number(new Date());
127 | let retVal = fn.apply(this, arguments);
128 | let durationMs = Number(new Date()) - start;
129 | log(fn.name + ': ' + (durationMs > 1000 ? `${(durationMs / 1000).toFixed(2)}s` : durationMs + 'ms'));
130 | return retVal;
131 | };
132 | }
--------------------------------------------------------------------------------
/src/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "identifier" : "net.nurik.roman.sketch.contrast",
3 | "compatibleVersion": 49,
4 | "bundleVersion": 1,
5 | "icon": "icon.png",
6 | "commands": [
7 | {
8 | "name": "Check type contrast for artboard",
9 | "handlers": {
10 | "run": "onCheckCurrentArtboard"
11 | },
12 | "identifier": "check-contrast",
13 | "script": "./commands.js",
14 | "shortcut" : "command option k",
15 | "description" : "Show a AA pass/fail type contrast report for current artboard.",
16 | "icon" : "icon.png"
17 | },
18 | {
19 | "name": "Check type contrast for this page",
20 | "handlers": {
21 | "run": "onCheckAllArtboards"
22 | },
23 | "identifier": "check-contrast-all",
24 | "script": "./commands.js",
25 | "description" : "Show/hide a AA pass/fail type contrast report for all artboards on the page inline.",
26 | "icon" : "icon.png"
27 | }
28 | ],
29 | "menu": {
30 | "title": "🌓 Contrast",
31 | "items": [
32 | "check-contrast",
33 | "check-contrast-all"
34 | ]
35 | }
36 | }
--------------------------------------------------------------------------------