Skip to content

Instantly share code, notes, and snippets.

@christianklotz
Last active July 21, 2020 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christianklotz/95ff9d329c9431064c428925b39ca45d to your computer and use it in GitHub Desktop.
Save christianklotz/95ff9d329c9431064c428925b39ca45d to your computer and use it in GitHub Desktop.
Create Sketch Assistant writing a custom rule
/**
Simple Assistant setting exactly one rule that ensures text layers are only using
specific fonts, in this case set to Comic Sans and Cochin.
1. Use Assistant Template from https://github.com/sketch-hq/sketch-assistant-template/
2. Find and replace all `sketch-assistant-template` with `sketch-comic-assistant`
3. Install dependencies
npm install
4. Replace src/index.ts with this gist's content
5. Create Assistant package
npm run package-tarball
6. Test resulting `.tgz` with your Sketch document via Assistants window › Manage Assistants… › Add from Archive…
*/
import { AssistantPackage, RuleDefinition, FileFormat } from '@sketch-hq/sketch-assistant-types'
const textFontAllowed: RuleDefinition = {
rule: async (context) => {
const { utils } = context
const allowedFonts: string[] = utils.getOption('allowedFonts')
let objects: Set<FileFormat.Text> = new Set()
for (const text of utils.objects.text) {
const font =
text.style?.textStyle?.encodedAttributes.MSAttributedStringFontAttribute.attributes.name
let pass = false
for (const f of allowedFonts) {
if (font?.startsWith(f)) {
pass = true
break
}
}
if (pass) continue
objects.add(text)
}
if (objects.size == 0) return
utils.report(`${objects.size} text layers are not using ${allowedFonts.join(', ')}`, ...objects)
},
name: 'sketch-comic-assistant/text-font-allowed',
title: 'Text must use Comic Sans',
description: 'Because Comic Sans is the best font in the world.',
getOptions: (helpers) => [
helpers.stringArrayOption({
name: 'allowedFonts',
title: 'Allowed Fonts',
description: 'The font family names that are allowed to be used.',
}),
],
}
const assistant: AssistantPackage = async () => {
return {
name: 'sketch-comic-assistant',
rules: [textFontAllowed],
config: {
rules: {
'sketch-comic-assistant/text-font-allowed': {
active: true,
allowedFonts: ['ComicSans', 'Cochin'],
},
},
},
}
}
export default assistant
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment