Coder Social home page Coder Social logo

plugin-typings's Introduction

Figma Plugin API typings

npm

This repository contains the typings for the Figma Plugin API.

Usage

  1. Installation

    npm i --save-dev @figma/plugin-typings
    # or
    yarn add -D @figma/plugin-typings
  2. Configure tsconfig.json

    {
        "compilerOptions": {
            "typeRoots": [
                "./node_modules/@types",
                "./node_modules/@figma"
            ]
        }
    }

    The configuration above is needed for the TypeScript compiler to use type definitions found in both ./node_modules/@types and ./node_modules/@figma. Normally, most external type definitions are from DefinitelyTyped and are installed in /@types, which included by TypeScript by default. Since we host the plugin typings separately, they are installed outside in /@figma instead.

    Types should become globally available without needing to use import statements. We do it this way because the plugin API is part of the host environment, as opposed to being a package that a plugin includes.

About

Plugin API releases have the format "Version X, Update Y". Equivalent tags are created in this repository as v<x>.<y>. Note that not all API releases include API changes, some are just bug fixes. Therefore, some typings versions are skipped.

plugin-typings's People

Contributors

abettadapur avatar ahurtado-figma avatar bdrebing avatar binji avatar bschlenk avatar caeleel avatar cjxh avatar delfu avatar elainefigma avatar elenathornton-figma avatar emartinfigma avatar grace-figma avatar james04321 avatar jefflee-figma avatar jlai-figma avatar joanna-chen avatar johndoherty avatar kristel-figma avatar lighthurst avatar lolzhang avatar robbiezhuang avatar rohitchouhan8 avatar roystbeef avatar rudi-c avatar sawyerhood avatar sicking avatar simplyahmazing avatar suyang581 avatar trev4ev avatar ymichael avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

plugin-typings's Issues

Conflicts between typings exposed globally

Description

When using figma plugin typing with typescript, an error occurs due to duplicate global type declaration.

node_modules/.pnpm/@[email protected]/node_modules/@figma/plugin-typings/index.d.ts:11:9 - error TS2451: Cannot redeclare block-scoped variable 'console'.

11   const console: Console
           ~~~~~~~

  node_modules/.pnpm/[email protected]/node_modules/typescript/lib/lib.dom.d.ts:16669:13
    16669 declare var console: Console;
                      ~~~~~~~
    'console' was also declared here.

node_modules/.pnpm/[email protected]/node_modules/typescript/lib/lib.dom.d.ts:16669:13 - error TS2451: Cannot redeclare block-scoped variable 'console'.

16669 declare var console: Console;
                  ~~~~~~~

  node_modules/.pnpm/@[email protected]/node_modules/@figma/plugin-typings/index.d.ts:11:9
    11   const console: Console
               ~~~~~~~
    'console' was also declared here.


Found 2 errors.

Reproduce

  1. Clone https://github.com/SoYoung210/figma-react-template
  2. remove comment out tsconfig.json, also figma.d.ts in root
{
  "compilerOptions": {
    "target": "es6",
    "lib": ["es6", "DOM"],
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "downlevelIteration": true,
    "noImplicitReturns": true,
    "jsx": "react-jsx",
    "typeRoots": [
      "./node_modules/@types",
      "./node_modules/@figma"
    ],
    "strict": false,
    "noUnusedLocals": true,
    "noUnusedParameters": true
  },
  "exclude": [
    "node_modules"
  ]
}
  1. run pnpm build(or just pnpm build:type)

Q1. Why are these types declared global in figma plugin?
It was added from #52, isn't it necessary to configure DOM lib to extend in tsconfig.json?

{
  "compilerOptions": {
    "target": "es6",
    "lib": ["es6", "DOM"],
  }
}

must extends DOM cause of react(in my project)

Q2. If keep the current type declaration, how can I bypass the type error in the reproduction repo?

Missing easing types

Hey,

I have the feeling that this line in the typings (

readonly type: "EASE_IN" | "EASE_OUT" | "EASE_IN_AND_OUT" | "LINEAR"
) should include ease_in_back, ease_out_back, ease_in_and_out_back.

Additionally the CUSTOM_CUBIC_BEZIER is not present and probably should be added as well.

Does that make sense @rudi-c or am I missing something?

provide order field on base node

order, as-is the index on the node hierarchy. seems like rest api supports order property, but plugin api does not.

Plans for adding this field on next update?

BooleaOperation is missing constraint peoperty (from ConstaintMixin)

this must be

 interface BooleanOperationNode extends DefaultShapeMixin, ChildrenMixin, CornerMixin {
    readonly type: "BOOLEAN_OPERATION"
    clone(): BooleanOperationNode
    booleanOperation: "UNION" | "INTERSECT" | "SUBTRACT" | "EXCLUDE"

    expanded: boolean
  }
export interface BooleanOperationNode
  extends DefaultShapeMixin,
    ChildrenMixin,
    // CUSTOM OVERRIDE
    // ---- this is not from official plugin typings, but exists. ---
    ConstraintMixin,
    // --------------------------------------------------------------
    CornerMixin {
  readonly type: "BOOLEAN_OPERATION";
  clone(): BooleanOperationNode;
  booleanOperation: "UNION" | "INTERSECT" | "SUBTRACT" | "EXCLUDE";

  expanded: boolean;
}

the constraint property exists on remote api

Missing support for ComponentNode documentationLinks to be cleared out (null value)

Hello there. I was using the new https://www.figma.com/plugin-docs/api/properties/ComponentNode-documentationlinks/ property, and as there is told, it is currently only supported to add one link. That's fine. But what's really missing here is that "clearing" out the field.

I built a plugin ("Bunch Description Change") where users can do different things with their' component descriptions. I am currently adding support for the "documentationLinks" property, but other than on the "description", where I can clear it (just like in the UI), with the "documentationLinks", I cannot clear it. This may cause confusion for the user of my plugin.

When I try to mutate it by saying component.documentationLinks = null, it throws me an error saying that it's not allowed. But also when trying this: component.documentationLinks = [{ uri: null }] (so exactly like in the docs) it also throws me an error saying that the type "null" is not allowed and a "string" type is required.

It would be really helpful if you could just allow setting an empty string/null so the field can clear up, just like you're possible to do in the UI. Thanks!

Set custom fontWeight on TextNode

Is it possible to set a random font weight via plugin api?
I can set fontName to a something like

{
  family: "Inter",
  style: "Regular"
}

which will correspond to fontWeight == 400, but if I want to set it to something in between, i.e. 450?

Parent property cannot be component set

Hello, I found this strange behavior on the 1.18.1 version.

If a create group components in a variant (ComponentSetNode) using the figma interface. The ComponentNode becomes the ComponentSetNode which is correct I think. But when I try to make a condition on the parent node type.

if ("COMPONENT" === node.type && node.parent && "COMPONENT_SET" === node.parent.type) { .... }

I get this typescript error :

TS2367: This condition will always return 'false' since the types '"COMPONENT_SET"' and '"COMPONENT" | "SLICE" | "FRAME" | "GROUP" | "INSTANCE" | "BOOLEAN_OPERATION" | "VECTOR" | "STAR" | "LINE" | "ELLIPSE" | "POLYGON" | "RECTANGLE" | "TEXT" | "DOCUMENT" | "PAGE"' have no overlap.

I found out that the parent property is typed like this :

readonly parent: (BaseNode & ChildrenMixin) | null

And BaseNode doesn't include ComponentSetNode.

Maybe we need to change parent property typing or BaseNode typing ?

Thank you for your answer :) And keep up the good work

VSCode linter broken in 1.39.0

The TS linter in VScode is unable to find any types from this library as of version 1.39.0.
image
Downgrading to 1.38.0 solves the issue.
image

Strangely, I am still able to compile source using types from this package at version 1.39.0, but the linter can't pick them up.

`variantProperties` can also be a string

It can be set to Component set for node has existing errors. This happens when you have invalid/duplicate variant(names).

The type definition should be something in the line of:

  interface VariantMixin {
    readonly variantProperties: { [property: string]: string } | null | string
  }

or:

  // I am unsure if this is allowed in a type definitions file
  const VariantErrorMessage = "Component set for node has existing errors";
  interface VariantMixin {
    readonly variantProperties: { [property: string]: string } | null | typeof VariantErrorMessage;
  }

Error: SyntaxError: possible import expression rejected around line 1

image

This is not the right place for posting this issue. but since figma does not have a adequate place for these issues on github, i'm posting here.

I have perfectly working fine module which runs on a browser, but when i import and run on figma platform it won't run with following error.

Error: SyntaxError: possible import expression rejected around line 1

I'm sorry i cannot provide more context, but figma does not provide any readable context either. can you contact developers team and check if this is a known issue or provide more context so i can find where to start with my debugging?

Referencing Agoric/agoric-sdk#43 (comment)

How to access "document" in code.ts?

Document is undefined in code.ts. I can't createElement('a') for download some styles data I get from figma API.
How to access "document" in code.ts?
So user can download the json generate by the plugin?
function downloadObjectAsJson(exportObj, exportName){
var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(exportObj));
var downloadAnchorNode = document.createElement('a');
downloadAnchorNode.setAttribute("href", dataStr);
downloadAnchorNode.setAttribute("download", exportName + ".json");
document.body.appendChild(downloadAnchorNode); // required for firefox
downloadAnchorNode.click();
downloadAnchorNode.remove();
}

Release 1.48.0?

Hey,

First of all, thank you for the hard work! Would it be possible for you to release version 1.48 with the recent changes?
That way, we could start using the new Figma features (one-side borders and absolutely positioned auto-layouts) in our Typescript plugins

Thanks!

No typings for fetch() signal parameter

Interface FetchOptions is missing a signal parameter of type AbortSignal, which is used to provide a timeout for the fetch request https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/timeout

  interface FetchOptions {
    method?: string
    headers?: { [name: string]: string }
    /**
     * @deprecated use headers instead
     */
    headersObject?: { [name: string]: string }
    body?: Uint8Array | string
    credentials?: string
    cache?: string
    redirect?: string
    referrer?: string
    integrity?: string
  }

In ComponentNode constraints field can be undefined

Hello Figma,

I'm working on a plugin and I notice that contraints field can be null for a ComponentNode. As the API documentation said : "Constraints of this node relative to its containing FrameNode, if any." So if the component is not in a frame the field doesn't exist in the node.

In the type system, ComponentNode extends DefaultFrameMixin which is composed by ConstraintMixin which defined constraints field as always present. I think we have to change this to match this behavior.

What do you think about it ?

Thank you for your help

Issues with `console` typings

See: #90 (comment)

11 const console: Console
~~~~~~~

../../../../usr/local/lib/node_modules/typescript/lib/lib.dom.d.ts:19124:13
19124 declare var console: Console;
~~~~~~~
'console' was also declared here.

../../../../usr/local/lib/node_modules/typescript/lib/lib.dom.d.ts:19124:13 - error TS2451: Cannot redeclare block-scoped variable 'console'.

19124 declare var console: Console;
~~~~~~~

node_modules/@figma/plugin-typings/index.d.ts:11:9
11 const console: Console
~~~~~~~
'console' was also declared here.

Found 2 errors.

Cannot set property fillGeometry of [object Object] which has only a getter

From plugin-api.d.ts, fillGeometry is not marked as readonly. I assumed I could edit the array but the Figma Developer VM threw this error: Cannot set property fillGeometry of [object Object] which has only a getter

const newVector = figma.createVector();
newVector.fillGeometry = [
  {windingRule: 'NONE', data: 'M 0 0 L 48 0 L 48 48 L 0 48 L 0 0 Z'},

All I'm trying to do is ensure the fills are kept after flattening, which is not deterministic at the moment (different FIgma clients have different results)

New line characters are not included in TextNode.characters

Reproduction:

  • Create a text with a new line (Shift + Enter) and a paragraph (Enter)

Screen Shot 2021-11-12 at 17 06 07

  • Inspect the TextNode in the console with (inside a plugin):
for (const node of figma.currentPage.selection) {
  console.log(node)
}
  • TextNode.characters does not contain new lines and paragraphs are converted to new lines instead:

Screen Shot 2021-11-12 at 17 01 40

Is there a way to get new lines of a TextNode?

Cannot find name 'figma'.

When I compile ts via tsc code.ts i get

code.ts:9:1 - error TS2304: Cannot find name 'figma'.

9 figma.showUI(__html__);
  ~~~~~

code.ts:9:14 - error TS2304: Cannot find name '__html__'.

9 figma.showUI(__html__);
               ~~~~~~~~

code.ts:14:1 - error TS2304: Cannot find name 'figma'.

14 figma.ui.onmessage = msg => {
   ~~~~~

code.ts:18:18 - error TS2304: Cannot find name 'SceneNode'.

18     const nodes: SceneNode[] = [];
                    ~~~~~~~~~

code.ts:20:20 - error TS2304: Cannot find name 'figma'.

20       const rect = figma.createRectangle();
                      ~~~~~

code.ts:23:7 - error TS2304: Cannot find name 'figma'.

23       figma.currentPage.appendChild(rect);
         ~~~~~

code.ts:26:5 - error TS2304: Cannot find name 'figma'.

26     figma.currentPage.selection = nodes;
       ~~~~~

code.ts:27:5 - error TS2304: Cannot find name 'figma'.

27     figma.viewport.scrollAndZoomIntoView(nodes);
       ~~~~~

code.ts:32:3 - error TS2304: Cannot find name 'figma'.

32   figma.closePlugin();
     ~~~~~


Found 9 errors.

Could you please fix it?

I installed the typings. My tsconfig looks like this:

  "compilerOptions": {
    "target": "es6",
    "lib": ["es6"],
    "typeRoots": [
      "./node_modules/@types",
      "./node_modules/@figma"
    ]
  }
}```

resize() function not taking variables

Hi, I am trying to resize line node.

const rowLine = figma.createLine();
rowLine.resize(908, 1);

When I add number variables it gives me this error message:
image

Is there some mistake in function or am I using it wrong?

Please export all types and interfaces.

Hello. I want to use types and interfaces without type inference.

I can't write code like below because d.ts file does not export anything.

const rgbToCss = (rgb: RGB): string => {
    const r = Math.round(rgb.r * 255);
    const g = Math.round(rgb.g * 255);
    const b = Math.round(rgb.b * 255);
    return `rgb(${r}, ${g}, ${b})`;
};

I created PR that exports all types and interfaces.

Thank you.

Cannot augment module 'console'

I have no clue why this error pops up or why my setup seems to be the only one complaining about this. The only fix i could imagine was adding a @ts-ignore above the index.d.ts:11:9.

node_modules/@figma/plugin-typings/index.d.ts:11:9 - error TS2649: Cannot augment module 'console' with value exports because it resolves to a non-module entity.

11   const console: Console
           ~~~~~~~

Cannot change STICKY size using `resize` method

Hi, I am trying to create some STICKY of different width and height (not 200X200) using API for my widget.

As suggested in StickyNode | Plugin API, width and height of sticky are all [read only] and I should use resize method. So my code was sticky.resize(item.width, item.height); but I got an error message Property 'resize' does not exist on type 'StickyNode'.

Also on Shared Node Properties | Plugin API , neither “resize” nor " resizeWithoutConstraints" section on this page includes stickyNodes.

[Bug] TextNode hasMissingFont method does not provide an accurate answer

Problem

When tried to resolve whether there are fonts missing within TextNode using hasMissingFont property it returns false.
Afterwards, by setting the characters property on the very same TextNode, an exception was thrown:

{
message: 'in set_characters: Cannot write to node with unloaded font "Roboto Medium". Please call figma.loadFontAsync({ family: "Roboto", style: "Medium" }) and await the returned promise first.',
}

Replication (simplified)

export const replicate = async () => {
  let missingFonts = [];

  const node = figma.getNodeById("I1:2004;42:1020");
  if (node.type === "TEXT") {
    if (node.hasMissingFont) { // this returns false
      missingFonts = node.getRangeAllFontNames(0, node.characters.length);

      if (missingFonts.length) {
        await Promise.all(missingFonts.map(async (font) => figma.loadFontAsync(font)));
      }
    }
    node.characters = "Updated text node"; // this throws an exception
  }
};

It seems like that the hasMissingFont property does not take into account a fontStyle (maybe).

Or am I missing anything?

unable to use typings with v 1.39.0

After updating to the latest version 1.39.0. Typings was not auto resolved.
found out /// <reference path="./plugin-api" /> in index.d.ts should contain file extension i.e plugin-api.d.ts
or else /// <reference types ="./plugin-api" />
and also const console: Console is conflicting with node.js globals so can you make const to var var console: Console

interface CurrentUser support?

Hi, I found current release not include figma.CurrentUser defined in index.d.ts

I notice pr#59 add above defination, but it's missing now.

Would you mind check the problem?

Thx for your time :)

[BUG] DestinationId does not exist on type Action

I am trying to destructure destinationId from Action and i receive the following:
Property 'destinationId' does not exist on type 'Action'.
Property 'destinationId' does not exist on type '{ readonly type: "BACK" | "CLOSE"; }'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.