common-tags#stripIndent TypeScript Examples

The following examples show how to use common-tags#stripIndent. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: codeGeneration.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
public typeAliasesForOperation(operation: Operation) {
    const { operationType, operationName, selectionSet } = operation;

    this.scopeStackPush(operationName);

    this.printer.enqueue(stripIndent`
      // ====================================================
      // GraphQL ${operationType} operation: ${operationName}
      // ====================================================
    `);

    // The root operation only has one variant
    // Do we need to get exhaustive variants anyway?
    const variants = this.getVariantsForSelectionSet(selectionSet);

    const variant = variants[0];
    const properties = this.getPropertiesForVariant(variant);

    const exportedTypeAlias = this.exportDeclaration(this.typeAliasObject(operationName, properties));

    this.printer.enqueue(exportedTypeAlias);
    this.scopeStackPop();
  }
Example #2
Source File: macro-assertions.ts    From typecheck.macro with MIT License 6 votes vote down vote up
ErrorBase = {
  ValidatorNoTypeParameter: `Failed to find type parameter. createValidator should be called with a type parameter. Example: "createValidator<TypeName>()"`,
  NotCalledAsFunction: `Macro should be called as function but was called as a`,
  MoreThanOneTypeParameter: `Macro should be called with 1 type parameter but was called with`,
  RegisterInvalidCall: stripIndent`
                                "register" should be called right below the type
                                declaration it is registering:
                                \`\`\`
                                interface Foo {
                                  bar: string
                                }
                                // no return value
                                register<Foo>()
                                \`\`\`
                                `,
  UnregisteredType: `Tried to generate a validator for an unregistered type with name`,
  // TODO: These will need to be updated once register accepts an options object
  RegisterInvalidNumberParams: `register should be called with 1 argument, but it was called with`,
  RegisterParam1NotStringLiteral: `register's first (and only) parameter should be a string literal, which is the name of the type to register, but it was a`,

  TypeDoesNotAcceptGenericParameters: `types don't accept generic parameters`,
  TooManyTypeParameters: `even though it only accepts`,
  NotEnoughTypeParameters: `type parameters even though it requires at least`,
  InvalidTypeParameterReference: `tried to reference the default type parameter in position:`,
}
Example #3
Source File: export-factory.ts    From vscode-code-review with MIT License 6 votes vote down vote up
private getCodeForFile(filename: string, lines: string): string {
    if (!filename) {
      filename = '';
    }
    if (!lines) {
      lines = '';
    }
    let result = '';
    const lineRanges = splitStringDefinition(lines); // split: 2:2-12:2|8:0-18:5
    const filePath = toAbsolutePath(this.workspaceRoot, filename);
    if (lineRanges) {
      lineRanges.forEach((rangeString: string) => {
        if (rangeString) {
          const range = rangeFromStringDefinition(rangeString, 1);
          const fileContent = stripIndent(getFileContentForRange(filePath, range));
          if (result) {
            result = `${result}${EOL}...${EOL}${EOL}${fileContent}`;
          } else {
            result = fileContent;
          }
        }
      });
    }
    return encode(result);
  }
Example #4
Source File: codeGeneration.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
function printEnumsAndInputObjects(generator: FlowAPIGenerator, context: CompilerContext) {
  generator.printer.enqueue(stripIndent`
    //==============================================================
    // START Enums and Input Objects
    // All enums and input objects are included in every output file
    // for now, but this will be changed soon.
    // TODO: Link to issue to fix this.
    //==============================================================
  `);

  context.typesUsed
    .filter(type => type instanceof GraphQLEnumType)
    .forEach(enumType => {
      generator.typeAliasForEnumType(enumType as GraphQLEnumType);
    });

  context.typesUsed
    .filter(type => type instanceof GraphQLInputObjectType)
    .forEach(inputObjectType => {
      generator.typeAliasForInputObjectType(inputObjectType as GraphQLInputObjectType);
    });

  generator.printer.enqueue(stripIndent`
    //==============================================================
    // END Enums and Input Objects
    //==============================================================
  `);
}
Example #5
Source File: Help.ts    From void-wa with GNU General Public License v3.0 6 votes vote down vote up
public async exec(msg: Message, args: string[]): Promise<void> {
        const handler = this.handler!;
        const command = handler.commands.get(args[0]) ?? Array.from(handler.commands.values()).find(x => x.options.aliases.includes(args[0]));
        if (!command) {
            let base = "*Command List*\n\n";
            const modules = handler.categories;
            for (const mod of modules) {
                base += `*${this.firstUpperCase(mod.name)}*\n${mod.commands.map(x => x.id).join(", ") || "None"}\n`;
            }
            await this.client.reply(msg.chatId, base, msg.id);
            return undefined;
        }
        const detail = stripIndent(`
        Command info for *${command.id}*
        _${command.options.description.content ? command.options.description.content : "No description available"}_

        *Aliases:* ${command.options.aliases.join(", ") || "No aliases"}
        *Usage:* ${command.options.description.usage ? `${msg.prefix}${command.id} ${command.options.description.usage}` : `${handler.prefix}${command.id}`}
        *Cooldown:* ${command.options.cooldown ? `${command.options.cooldown}s` : "10s"}

        ℹ️ _<> means required and [ ] means optional, don't include <> or [ ] when using command._
        `);
        await this.client.reply(msg.chatId, detail, msg.id);
    }
Example #6
Source File: tokenProcessors.ts    From vkui-tokens with MIT License 6 votes vote down vote up
customMediaDeclaration = {
	[EStyleTypes.CSS]: null,

	[EStyleTypes.PCSS]: (key, token, postfix = '') =>
		`@custom-media --${unCamelcasify(key)}${postfix} ${token};\n`,

	[EStyleTypes.SCSS]: (key, token, postfix = '') =>
		`${stripIndent`
		@mixin media-${unCamelcasify(key)}${postfix} {
			@media ${token} { @content; }
		}`}\n`,

	[EStyleTypes.LESS]: (key, token, postfix = '') =>
		`${stripIndent`
		.media-${unCamelcasify(key)}${postfix}(@content) {
			@media ${token} { @content; }
		}`}\n`,

	[EStyleTypes.STYL]: (key, token, postfix = '') =>
		`${stripIndent`
		media-${unCamelcasify(key)}${postfix}(content) {
			@media ${token} { content }
		}`}\n`,
} as const
Example #7
Source File: compileGetDeclarationString.ts    From vkui-tokens with MIT License 6 votes vote down vote up
export function compileGetDeclarationString<T = Theme>(
	sourceTheme: ThemeCssVarsWide<T>,
	type: DeclarationType = 'default',
): string {
	const theme: ThemeCssVarsWide<T> =
		type === 'onlyColors' ? getOnlyColors(sourceTheme) : sourceTheme;

	const {flatValues} = accumulateValues({
		theme,
	});

	return stripIndent`
	import {Properties} from 'csstype';

	export function getDeclarationVar${
		type === 'onlyColors' ? 'Colors' : ''
	}String(): string {
		return \`${getVarString({
			valuesObject: flatValues,
			prefix: '',
			delimeter: '',
		})}\`;
	}

	export function getDeclarationVar${
		type === 'onlyColors' ? 'Colors' : ''
	}Object(): Properties {
		return ${JSON.stringify(flatValues)} as Properties;
	}
	`;
}
Example #8
Source File: codeGeneration.ts    From amplify-codegen with Apache License 2.0 5 votes vote down vote up
fileHeader() {
    this.printer.enqueue(
      stripIndent`
        /* @flow */
        // This file was automatically generated and should not be edited.
      `
    );
  }
Example #9
Source File: codeGeneration.ts    From amplify-codegen with Apache License 2.0 5 votes vote down vote up
public typeAliasesForFragment(fragment: Fragment) {
    const { fragmentName, selectionSet } = fragment;

    this.scopeStackPush(fragmentName);

    this.printer.enqueue(stripIndent`
      // ====================================================
      // GraphQL fragment: ${fragmentName}
      // ====================================================
    `);

    const variants = this.getVariantsForSelectionSet(selectionSet);

    if (variants.length === 1) {
      const properties = this.getPropertiesForVariant(variants[0]);

      const name = this.annotationFromScopeStack(this.scopeStack).id.name;
      const exportedTypeAlias = this.exportDeclaration(this.typeAliasObject(name, properties));

      this.printer.enqueue(exportedTypeAlias);
    } else {
      const unionMembers: t.FlowTypeAnnotation[] = [];
      variants.forEach(variant => {
        this.scopeStackPush(variant.possibleTypes[0].toString());
        const properties = this.getPropertiesForVariant(variant);

        const name = this.annotationFromScopeStack(this.scopeStack).id.name;
        const exportedTypeAlias = this.exportDeclaration(this.typeAliasObject(name, properties));

        this.printer.enqueue(exportedTypeAlias);

        unionMembers.push(this.annotationFromScopeStack(this.scopeStack));

        this.scopeStackPop();
      });

      this.printer.enqueue(
        this.exportDeclaration(this.typeAliasGenericUnion(this.annotationFromScopeStack(this.scopeStack).id.name, unionMembers))
      );
    }

    this.scopeStackPop();
  }
Example #10
Source File: printer.ts    From amplify-codegen with Apache License 2.0 5 votes vote down vote up
/**
   * When using trailing commas on ObjectTypeProperties within
   * ObjectTypeAnnotations, we get weird behavior:
   * ```
   * {
   *   homePlanet: ?string // description
   *   ,
   *   friends: any  // description
   * }
   * ```
   * when we want
   * ```
   * {
   *   homePlanet: ?string, // description
   *   friends: any         // description
   * }
   * ```
   */
  private fixCommas(documentPart: string) {
    const lines = documentPart.split('\n');
    let currentLine = 0;
    let nextLine;
    const newDocumentParts = [];
    // Keep track of what column comments should start on
    // to keep things aligned
    let maxCommentColumn = 0;

    while (currentLine !== lines.length) {
      nextLine = currentLine + 1;
      const strippedNextLine = stripIndent`${lines[nextLine]}`;
      if (strippedNextLine.length === 1 && strippedNextLine[0] === ',') {
        const currentLineContents = lines[currentLine];
        const commentColumn = currentLineContents.indexOf('//');
        if (maxCommentColumn < commentColumn) {
          maxCommentColumn = commentColumn;
        }

        const [contents, comment] = currentLineContents.split('//');
        newDocumentParts.push({
          main: contents.replace(/\s+$/g, '') + ',',
          comment: comment.trim(),
        });
        currentLine++;
      } else {
        newDocumentParts.push({
          main: lines[currentLine],
          comment: null,
        });
      }

      currentLine++;
    }

    return newDocumentParts
      .reduce((memo: string[], part) => {
        const { main, comment } = part;

        let line;
        if (comment !== null) {
          const spacesBetween = maxCommentColumn - main.length;
          line = `${main}${' '.repeat(spacesBetween)} // ${comment}`;
        } else {
          line = main;
        }

        return [...memo, line];
      }, [])
      .join('\n');
  }
Example #11
Source File: comment.test.ts    From genql with MIT License 5 votes vote down vote up
stripAndWrap = (tsa: TemplateStringsArray) => `\n${stripIndent(tsa)}\n`
Example #12
Source File: compileStyles.ts    From vkui-tokens with MIT License 4 votes vote down vote up
compileStyles = <PT extends PixelifyTheme = PixelifyTheme>(
	format: Formats,
	theme: PT,
	mode: CompileStylesMode = 'default',
	themeBase?: PT,
	// eslint-disable-next-line sonarjs/cognitive-complexity
): string => {
	const classicCssType = isClassicCssType(format);
	const prefix = getPrefix(format, theme);
	const rootSelector = getRootSelector(theme, mode);
	const incremental = isIncremental(mode);

	const getDeclaration = varDeclarations[format];
	const getVariableStatement = variablesStatementDeclaration[format];
	const getCustomMediaDeclaration = customMediaDeclaration[format];

	let result = '';
	let variables = '';
	let groupTokens = '';

	switch (mode) {
		case 'onlyColors':
			theme = getOnlyColors(theme);
			break;

		case 'noSizes':
			theme = getAllButSizes(theme, (theme as any).themeNameBase);
			break;

		case 'noColors':
			theme = getAllButColors(theme, (theme as any).themeNameBase);
			break;
	}

	Object.keys(theme).forEach((key) => {
		// пропускаем служебные ключи
		if (serviceKeys.includes(key)) {
			return;
		}

		const token = theme[key];

		// в инкрементальном режиме пропускаем токены, чьи значения совпадают со значениями из themeBase
		if (incremental && themeBase && isDeepEqual(token, themeBase[key])) {
			return;
		}

		// если переменная — строка (например, имя темы)
		if (isString(token, key)) {
			variables += getVariableStatement(
				getDeclaration(key, prefix),
				`'${CSS.escape(token)}'`,
			);
			return;
		}

		// если переменная — цвет
		if (isColor(token)) {
			Object.keys(token).forEach((colorState) => {
				const value = token[colorState];

				variables += getVariableStatement(
					getDeclaration(key, prefix),
					value,
					colorState !== 'normal' ? `--${colorState}` : '',
				);
			});
			return;
		}

		// если переменная — это объект (группа значений)
		// например — шрифты
		if (isGroupToken(token)) {
			const groupTokenResult = processGroupToken({
				format,
				prefix,
				token,
				key,
				adaptiveMode: mode as any,
			});

			variables += groupTokenResult.variables;
			groupTokens += groupTokenResult.groupTokens;
			return;
		}

		if (isAdaptiveFlatToken(token)) {
			Object.keys(token).forEach((adaptivivityState) => {
				const value = token[adaptivivityState];

				variables += getVariableStatement(
					getDeclaration(key, prefix),
					value,
					`--${unCamelcasify(
						adaptivivityState,
						classicCssType ? '_' : '-',
					)}`,
				);
			});
			return;
		}

		if (isCustomMediaToken(key)) {
			if (getCustomMediaDeclaration) {
				groupTokens += getCustomMediaDeclaration(key, token);
			}
			return;
		}

		// обычная переменная
		variables += getVariableStatement(getDeclaration(key, prefix), token);
	});

	result = variables;

	if (classicCssType && variables) {
		result = stripIndent`
		${rootSelector} {
		${variables.split('\n').join('\n\t\t')}}
		`;
	}

	if (isOnlyVariables(mode)) {
		return stripIndent(result);
	}

	if (mode === 'onlyAdaptiveGroups') {
		return stripIndent(groupTokens);
	}

	result += `\n\n${groupTokens}`;

	return stripIndent(result);
}
Example #13
Source File: compileStyles.test.ts    From vkui-tokens with MIT License 4 votes vote down vote up
describe('compileStyles', () => {
	test.each(formats)('%s: should compile colors', (format) => {
		runTest(format, {
			descriptionTheme: {
				themeName: 'testTheme',
				colorsScheme: 'light',
				colorAccent: {
					normal: 'blue',
					hover: 'darkblue',
					active: 'darkslateblue',
				},
			},
			result: {
				css: stripIndent`
				:root {
					--vkui--theme_name: 'testTheme';
					--vkui--colors_scheme: light;
					--vkui--color_accent: blue;
					--vkui--color_accent--hover: darkblue;
					--vkui--color_accent--active: darkslateblue;
				}
				`,
				scss: stripIndent`
					$theme-name: 'testTheme';
					$colors-scheme: light;
					$color-accent: blue;
					$color-accent--hover: darkblue;
					$color-accent--active: darkslateblue;
				`,
				pcss: stripIndent`
				:root {
					--theme-name: 'testTheme';
					--colors-scheme: light;
					--color-accent: blue;
					--color-accent--hover: darkblue;
					--color-accent--active: darkslateblue;
				}
				`,
				less: stripIndent`
				@theme-name: 'testTheme';
				@colors-scheme: light;
				@color-accent: blue;
				@color-accent--hover: darkblue;
				@color-accent--active: darkslateblue;
				`,
				styl: stripIndent`
				$theme-name = 'testTheme';
				$colors-scheme = light;
				$color-accent = blue;
				$color-accent--hover = darkblue;
				$color-accent--active = darkslateblue;
				`,
			},
		});
	});

	test.each(formats)('%s: should compile flat class variables', (format) => {
		runTest(format, {
			descriptionTheme: {
				themeName: 'testTheme',
				colorsScheme: 'light',
				fontSome: {
					fontSize: '16px',
					lineHeight: '25px',
				},
			} as any,
			result: {
				css: stripIndent`
				:root {
					--vkui--theme_name: 'testTheme';
					--vkui--colors_scheme: light;
					--vkui--font_some--font_size: 16px;
					--vkui--font_some--line_height: 25px;
				}

				.vkui--font_some {
					font-size: 16px;
					font-size: var(--vkui--font_some--font_size, 16px);
					line-height: 25px;
					line-height: var(--vkui--font_some--line_height, 25px);
				}
				`,
				scss: stripIndent`
				$theme-name: 'testTheme';
				$colors-scheme: light;


				@mixin font-some() {
					font-size: 16px;
					line-height: 25px;
				}
				$font-some--map: (
					'fontSize': 16px,
					'lineHeight': 25px,
				);
				`,
				pcss: stripIndent`
				:root {
					--theme-name: 'testTheme';
					--colors-scheme: light;
				}

				%font-some {
					font-size: 16px;
					line-height: 25px;
				}
				`,
				less: stripIndent`
				@theme-name: 'testTheme';
				@colors-scheme: light;


				.font-some {
					font-size: 16px;
					line-height: 25px;
				}
				`,

				styl: stripIndent`
				$theme-name = 'testTheme';
				$colors-scheme = light;


				font-some() {
					font-size: 16px;
					line-height: 25px;
				}
				`,
			},
		});
	});

	test.each(formats)('%s: should compile adaptive class variables', (f) => {
		runTest(f, {
			descriptionTheme: {
				themeName: 'testTheme',
				colorsScheme: 'light',
				fontText: {
					regular: {
						fontSize: '15px',
						lineHeight: '20px',
						fontFamily: 'Arial',
						fontWeight: 500,
					},
					compactX: {
						fontSize: '16px',
						lineHeight: '24px',
					},
				},
			},
			result: {
				css: stripIndent`
				:root {
					--vkui--theme_name: 'testTheme';
					--vkui--colors_scheme: light;
					--vkui--font_text--font_size--regular: 15px;
					--vkui--font_text--line_height--regular: 20px;
					--vkui--font_text--font_family--regular: Arial;
					--vkui--font_text--font_weight--regular: 500;
					--vkui--font_text--font_size--compact_x: 16px;
					--vkui--font_text--line_height--compact_x: 24px;
				}

				.vkui--font_text--regular {
					font-size: 15px;
					font-size: var(--vkui--font_text--font_size--regular, 15px);
					line-height: 20px;
					line-height: var(--vkui--font_text--line_height--regular, 20px);
					font-family: Arial;
					font-family: var(--vkui--font_text--font_family--regular, Arial);
					font-weight: 500;
					font-weight: var(--vkui--font_text--font_weight--regular, 500);
				}
				.vkui--font_text--compact-x {
					font-size: 16px;
					font-size: var(--vkui--font_text--font_size--compact_x, 16px);
					line-height: 24px;
					line-height: var(--vkui--font_text--line_height--compact_x, 24px);
					font-family: Arial;
					font-family: var(--vkui--font_text--font_family--regular, Arial);
					font-weight: 500;
					font-weight: var(--vkui--font_text--font_weight--regular, 500);
				}
				`,
				scss: stripIndent`
				$theme-name: 'testTheme';
				$colors-scheme: light;


				@mixin font-text--regular() {
					font-size: 15px;
					line-height: 20px;
					font-family: Arial;
					font-weight: 500;
				}
				$font-text--regular--map: (
					'fontSize': 15px,
					'lineHeight': 20px,
					'fontFamily': Arial,
					'fontWeight': 500,
				);
				@mixin font-text--compact-x() {
					font-size: 16px;
					line-height: 24px;
					font-family: Arial;
					font-weight: 500;
				}
				$font-text--regular--map: (
					'fontSize': 15px,
					'lineHeight': 20px,
					'fontFamily': Arial,
					'fontWeight': 500,
				);
				$font-text--compact-x--map: (
					'fontSize': 16px,
					'lineHeight': 24px,
					'fontFamily': Arial,
					'fontWeight': 500,
				);
				`,
				pcss: stripIndent`
				:root {
					--theme-name: 'testTheme';
					--colors-scheme: light;
				}

				%font-text--regular {
					font-size: 15px;
					line-height: 20px;
					font-family: Arial;
					font-weight: 500;
				}
				%font-text--compact-x {
					font-size: 16px;
					line-height: 24px;
					font-family: Arial;
					font-weight: 500;
				}
				`,
				less: stripIndent`
				@theme-name: 'testTheme';
				@colors-scheme: light;


				.font-text--regular {
					font-size: 15px;
					line-height: 20px;
					font-family: Arial;
					font-weight: 500;
				}
				.font-text--compact-x {
					font-size: 16px;
					line-height: 24px;
					font-family: Arial;
					font-weight: 500;
				}
				`,

				styl: stripIndent`
				$theme-name = 'testTheme';
				$colors-scheme = light;


				font-text--regular() {
					font-size: 15px;
					line-height: 20px;
					font-family: Arial;
					font-weight: 500;
				}
				font-text--compact-x() {
					font-size: 16px;
					line-height: 24px;
					font-family: Arial;
					font-weight: 500;
				}
				`,
			},
		});
	});

	test.each(formats)('%s: should compile adaptive flat variables', (f) => {
		runTest(f, {
			descriptionTheme: {
				themeName: 'testTheme',
				colorsScheme: 'light',
				sizePopupBasePadding: {
					compact: '20px',
					regular: '32px',
					large: '40px',
					largeX: '50px',
				},
			},
			result: {
				css: stripIndent`
				:root {
					--vkui--theme_name: 'testTheme';
					--vkui--colors_scheme: light;
					--vkui--size_popup_base_padding--compact: 20px;
					--vkui--size_popup_base_padding--regular: 32px;
					--vkui--size_popup_base_padding--large: 40px;
					--vkui--size_popup_base_padding--large_x: 50px;
				}
				`,
				scss: stripIndent`
				$theme-name: 'testTheme';
				$colors-scheme: light;
				$size-popup-base-padding--compact: 20px;
				$size-popup-base-padding--regular: 32px;
				$size-popup-base-padding--large: 40px;
				$size-popup-base-padding--large-x: 50px;
				`,
				pcss: stripIndent`
				:root {
					--theme-name: 'testTheme';
					--colors-scheme: light;
					--size-popup-base-padding--compact: 20px;
					--size-popup-base-padding--regular: 32px;
					--size-popup-base-padding--large: 40px;
					--size-popup-base-padding--large_x: 50px;
				}
				`,
				less: stripIndent`
				@theme-name: 'testTheme';
				@colors-scheme: light;
				@size-popup-base-padding--compact: 20px;
				@size-popup-base-padding--regular: 32px;
				@size-popup-base-padding--large: 40px;
				@size-popup-base-padding--large-x: 50px;
				`,

				styl: stripIndent`
				$theme-name = 'testTheme';
				$colors-scheme = light;
				$size-popup-base-padding--compact = 20px;
				$size-popup-base-padding--regular = 32px;
				$size-popup-base-padding--large = 40px;
				$size-popup-base-padding--large-x = 50px;
				`,
			},
		});
	});

	test.each(formats)('%s: should compile flat variables', (f) => {
		runTest(f, {
			descriptionTheme: {
				themeName: 'testTheme',
				colorsScheme: 'light',
				opacityDisable: 0.4,
			},
			result: {
				css: stripIndent`
				:root {
					--vkui--theme_name: 'testTheme';
					--vkui--colors_scheme: light;
					--vkui--opacity_disable: 0.4;
				}
				`,
				scss: stripIndent`
				$theme-name: 'testTheme';
				$colors-scheme: light;
				$opacity-disable: 0.4;
				`,
				pcss: stripIndent`
				:root {
					--theme-name: 'testTheme';
					--colors-scheme: light;
					--opacity-disable: 0.4;
				}
				`,
				less: stripIndent`
				@theme-name: 'testTheme';
				@colors-scheme: light;
				@opacity-disable: 0.4;
				`,

				styl: stripIndent`
				$theme-name = 'testTheme';
				$colors-scheme = light;
				$opacity-disable = 0.4;
				`,
			},
		});
	});

	test.each(formats)('%s: should compile media queries', (f) => {
		runTest(f, {
			descriptionTheme: {
				themeName: 'testTheme',
				colorsScheme: 'light',
				widthTablet: '(min-width: 768px) and (max-width: 999px)',
				widthToDesktopL: '(max-width: 2199px)',
			},
			result: {
				css: stripIndent`
				:root {
					--vkui--theme_name: 'testTheme';
					--vkui--colors_scheme: light;
				}`,
				scss: stripIndent`
				$theme-name: 'testTheme';
				$colors-scheme: light;


				@mixin media-width-tablet {
					@media (min-width: 768px) and (max-width: 999px) { @content; }
				}
				@mixin media-width-to-desktop-l {
					@media (max-width: 2199px) { @content; }
				}
				`,
				pcss: stripIndent`
				:root {
					--theme-name: 'testTheme';
					--colors-scheme: light;
				}

				@custom-media --width-tablet (min-width: 768px) and (max-width: 999px);
				@custom-media --width-to-desktop-l (max-width: 2199px);
				`,
				less: stripIndent`
				@theme-name: 'testTheme';
				@colors-scheme: light;


				.media-width-tablet(@content) {
					@media (min-width: 768px) and (max-width: 999px) { @content; }
				}
				.media-width-to-desktop-l(@content) {
					@media (max-width: 2199px) { @content; }
				}
				`,

				styl: stripIndent`
				$theme-name = 'testTheme';
				$colors-scheme = light;


				media-width-tablet(content) {
					@media (min-width: 768px) and (max-width: 999px) { content }
				}
				media-width-to-desktop-l(content) {
					@media (max-width: 2199px) { content }
				}
				`,
			},
		});
	});

	test.each(formats)(
		'%s: should compile adaptive class variables with onlyAdaptiveGroups',
		(f) => {
			runTest(f, {
				descriptionTheme: {
					themeName: 'testTheme',
					colorsScheme: 'light',
					fontText: {
						regular: {
							fontSize: '15px',
							lineHeight: '20px',
							fontFamily: 'Arial',
							fontWeight: 500,
						},
						compact: {
							fontSize: '16px',
							lineHeight: '24px',
						},
					},
				},
				mode: 'onlyAdaptiveGroups',
				result: {
					css: stripIndent`
				.vkui--font_text {
					font-size: var(--vkui--font_text--font_size);
					line-height: var(--vkui--font_text--line_height);
					font-family: var(--vkui--font_text--font_family);
					font-weight: var(--vkui--font_text--font_weight);
				}
				`,
					scss: stripIndent``,
					pcss: stripIndent``,
					less: stripIndent``,

					styl: stripIndent``,
				},
			});
		},
	);

	test.each(formats)(
		'%s: should compile adaptive class variables with mode=withAdaptiveGroups',
		(f) => {
			runTest(f, {
				mode: 'withAdaptiveGroups',
				descriptionTheme: {
					themeName: 'testTheme',
					colorsScheme: 'light',
					fontText: {
						regular: {
							fontSize: '15px',
							lineHeight: '20px',
							fontFamily: 'Arial',
							fontWeight: 500,
						},
						compact: {
							fontSize: '16px',
							lineHeight: '24px',
						},
					},
				},
				result: {
					css: stripIndent`
				:root {
					--vkui--theme_name: 'testTheme';
					--vkui--colors_scheme: light;
					--vkui--font_text--font_size--regular: 15px;
					--vkui--font_text--line_height--regular: 20px;
					--vkui--font_text--font_family--regular: Arial;
					--vkui--font_text--font_weight--regular: 500;
					--vkui--font_text--font_size--compact: 16px;
					--vkui--font_text--line_height--compact: 24px;
				}

				.vkui--font_text--regular {
					font-size: 15px;
					font-size: var(--vkui--font_text--font_size--regular, 15px);
					line-height: 20px;
					line-height: var(--vkui--font_text--line_height--regular, 20px);
					font-family: Arial;
					font-family: var(--vkui--font_text--font_family--regular, Arial);
					font-weight: 500;
					font-weight: var(--vkui--font_text--font_weight--regular, 500);
				}
				.vkui--font_text {
					font-size: var(--vkui--font_text--font_size);
					line-height: var(--vkui--font_text--line_height);
					font-family: var(--vkui--font_text--font_family);
					font-weight: var(--vkui--font_text--font_weight);
				}
				.vkui--font_text--compact {
					font-size: 16px;
					font-size: var(--vkui--font_text--font_size--compact, 16px);
					line-height: 24px;
					line-height: var(--vkui--font_text--line_height--compact, 24px);
					font-family: Arial;
					font-family: var(--vkui--font_text--font_family--regular, Arial);
					font-weight: 500;
					font-weight: var(--vkui--font_text--font_weight--regular, 500);
				}
				`,
					scss: stripIndent`
				$theme-name: 'testTheme';
				$colors-scheme: light;


				@mixin font-text--regular() {
					font-size: 15px;
					line-height: 20px;
					font-family: Arial;
					font-weight: 500;
				}
				$font-text--regular--map: (
					'fontSize': 15px,
					'lineHeight': 20px,
					'fontFamily': Arial,
					'fontWeight': 500,
				);
				@mixin font-text--compact() {
					font-size: 16px;
					line-height: 24px;
					font-family: Arial;
					font-weight: 500;
				}
				$font-text--regular--map: (
					'fontSize': 15px,
					'lineHeight': 20px,
					'fontFamily': Arial,
					'fontWeight': 500,
				);
				$font-text--compact--map: (
					'fontSize': 16px,
					'lineHeight': 24px,
					'fontFamily': Arial,
					'fontWeight': 500,
				);
				`,
					pcss: stripIndent`
				:root {
					--theme-name: 'testTheme';
					--colors-scheme: light;
				}

				%font-text--regular {
					font-size: 15px;
					line-height: 20px;
					font-family: Arial;
					font-weight: 500;
				}
				%font-text--compact {
					font-size: 16px;
					line-height: 24px;
					font-family: Arial;
					font-weight: 500;
				}
				`,
					less: stripIndent`
				@theme-name: 'testTheme';
				@colors-scheme: light;


				.font-text--regular {
					font-size: 15px;
					line-height: 20px;
					font-family: Arial;
					font-weight: 500;
				}
				.font-text--compact {
					font-size: 16px;
					line-height: 24px;
					font-family: Arial;
					font-weight: 500;
				}
				`,

					styl: stripIndent`
				$theme-name = 'testTheme';
				$colors-scheme = light;


				font-text--regular() {
					font-size: 15px;
					line-height: 20px;
					font-family: Arial;
					font-weight: 500;
				}
				font-text--compact() {
					font-size: 16px;
					line-height: 24px;
					font-family: Arial;
					font-weight: 500;
				}
				`,
				},
			});
		},
	);

	test.each(formats)('%s: should compile onlyColors', (f) => {
		runTest(f, {
			mode: 'onlyColors',
			descriptionTheme: {
				themeName: 'testTheme',
				colorsScheme: 'light',
				sizeBasePadding: {
					regular: 20,
				},
				colorBackground: {
					normal: '#FFF',
					hover: '#AAA',
					active: '#CCC',
				},
			},
			result: {
				css: stripIndent`
					:root {
						--vkui--color_background: #FFF;
						--vkui--color_background--hover: #AAA;
						--vkui--color_background--active: #CCC;
					}
				`,
				scss: stripIndent`
					$color-background: #FFF;
					$color-background--hover: #AAA;
					$color-background--active: #CCC;
				`,
				pcss: stripIndent`
				:root {
					--color-background: #FFF;
					--color-background--hover: #AAA;
					--color-background--active: #CCC;
				}`,
				less: stripIndent`
					@color-background: #FFF;
					@color-background--hover: #AAA;
					@color-background--active: #CCC;
				`,
				styl: stripIndent`
					$color-background = #FFF;
					$color-background--hover = #AAA;
					$color-background--active = #CCC;
				`,
			},
		});
	});

	test.each(formats)('%s: should compile noSizes', (f) => {
		runTest(f, {
			mode: 'noSizes',
			descriptionTheme: {
				themeName: 'testTheme',
				colorsScheme: 'light',
				sizeBasePadding: {
					regular: 20,
				},
				colorBackground: {
					normal: '#FFF',
					hover: '#AAA',
					active: '#CCC',
				},
			},
			result: {
				css: stripIndent`
					:root {
						--vkui--theme_name: 'testTheme';
						--vkui--colors_scheme: light;
						--vkui--color_background: #FFF;
						--vkui--color_background--hover: #AAA;
						--vkui--color_background--active: #CCC;
					}
				`,
				scss: stripIndent`
					$theme-name: 'testTheme';
					$colors-scheme: light;
					$color-background: #FFF;
					$color-background--hover: #AAA;
					$color-background--active: #CCC;
				`,
				pcss: stripIndent`
				:root {
					--theme-name: 'testTheme';
					--colors-scheme: light;
					--color-background: #FFF;
					--color-background--hover: #AAA;
					--color-background--active: #CCC;
				}`,
				less: stripIndent`
					@theme-name: 'testTheme';
					@colors-scheme: light;
					@color-background: #FFF;
					@color-background--hover: #AAA;
					@color-background--active: #CCC;
				`,
				styl: stripIndent`
					$theme-name = 'testTheme';
					$colors-scheme = light;
					$color-background = #FFF;
					$color-background--hover = #AAA;
					$color-background--active = #CCC;
				`,
			},
		});
	});

	test.each(formats)('%s: should compile noColors', (f) => {
		runTest(f, {
			mode: 'noColors',
			descriptionTheme: {
				themeName: 'testTheme',
				colorsScheme: 'light',
				sizeBasePadding: {
					regular: '20px',
				},
				colorBackground: {
					normal: '#FFF',
					hover: '#AAA',
					active: '#CCC',
				},
			},
			result: {
				css: stripIndent`
					:root {
						--vkui--theme_name: 'testTheme';
						--vkui--size_base_padding--regular: 20px;
					}
				`,
				scss: stripIndent`
					$theme-name: 'testTheme';
					$size-base-padding--regular: 20px;
				`,
				pcss: stripIndent`
				:root {
					--theme-name: 'testTheme';
					--size-base-padding--regular: 20px;
				}`,
				less: stripIndent`
					@theme-name: 'testTheme';
					@size-base-padding--regular: 20px;
				`,
				styl: stripIndent`
					$theme-name = 'testTheme';
					$size-base-padding--regular = 20px;
				`,
			},
		});
	});

	test.each(formats)('%s: customized selector in onlyVariablesLocal', (f) => {
		runTest(f, {
			mode: 'onlyVariablesLocal',
			descriptionTheme: {
				themeName: 'vkIOSDark',
				themeNameBase: 'vkIOS',
				colorsScheme: 'dark',
				colorBackground: {
					normal: '#FFF',
					hover: '#AAA',
					active: '#CCC',
				},
			},
			result: {
				css: stripIndent`
					.vkui--vkIOS--dark {
						--vkui--theme_name: 'vkIOSDark';
						--vkui--theme_name_base: 'vkIOS';
						--vkui--colors_scheme: dark;
						--vkui--color_background: #FFF;
						--vkui--color_background--hover: #AAA;
						--vkui--color_background--active: #CCC;
					}
				`,
				scss: stripIndent`
					$theme-name: 'vkIOSDark';
					$theme-name-base: 'vkIOS';
					$colors-scheme: dark;
					$color-background: #FFF;
					$color-background--hover: #AAA;
					$color-background--active: #CCC;
				`,
				pcss: stripIndent`
				.vkui--vkIOS--dark {
					--theme-name: 'vkIOSDark';
					--theme-name-base: 'vkIOS';
					--colors-scheme: dark;
					--color-background: #FFF;
					--color-background--hover: #AAA;
					--color-background--active: #CCC;
				}`,
				less: stripIndent`
					@theme-name: 'vkIOSDark';
					@theme-name-base: 'vkIOS';
					@colors-scheme: dark;
					@color-background: #FFF;
					@color-background--hover: #AAA;
					@color-background--active: #CCC;
				`,
				styl: stripIndent`
					$theme-name = 'vkIOSDark';
					$theme-name-base = 'vkIOS';
					$colors-scheme = dark;
					$color-background = #FFF;
					$color-background--hover = #AAA;
					$color-background--active = #CCC;
				`,
			},
		});
	});

	test.each(formats)('%s: onlyVariablesLocalIncremental', (f) => {
		runTest(f, {
			mode: 'onlyVariablesLocalIncremental',
			descriptionTheme: {
				themeName: 'vkIOSDark',
				themeNameBase: 'vkIOS',
				themeInheritsFrom: 'vkIOS',
				colorsScheme: 'dark',
				sizeBasePadding: {
					regular: '20px',
				},
				colorBackground: {
					normal: '#FFF',
					hover: '#AAA',
					active: '#CCC',
				},
			},
			descriptionThemeBase: {
				themeName: 'vkIOS',
				colorsScheme: 'light',
				sizeBasePadding: {
					regular: '20px',
				},
				colorBackground: {
					normal: '#AAA',
					hover: '#AAA',
					active: '#CCC',
				},
			},
			result: {
				css: stripIndent`
					.vkui--vkIOS--dark {
						--vkui--theme_name: 'vkIOSDark';
						--vkui--theme_name_base: 'vkIOS';
						--vkui--theme_inherits_from: 'vkIOS';
						--vkui--colors_scheme: dark;
						--vkui--color_background: #FFF;
						--vkui--color_background--hover: #AAA;
						--vkui--color_background--active: #CCC;
					}
				`,
				scss: stripIndent`
					$theme-name: 'vkIOSDark';
					$theme-name-base: 'vkIOS';
					$theme-inherits-from: 'vkIOS';
					$colors-scheme: dark;
					$color-background: #FFF;
					$color-background--hover: #AAA;
					$color-background--active: #CCC;
				`,
				pcss: stripIndent`
				.vkui--vkIOS--dark {
					--theme-name: 'vkIOSDark';
					--theme-name-base: 'vkIOS';
					--theme-inherits-from: 'vkIOS';
					--colors-scheme: dark;
					--color-background: #FFF;
					--color-background--hover: #AAA;
					--color-background--active: #CCC;
				}`,
				less: stripIndent`
					@theme-name: 'vkIOSDark';
					@theme-name-base: 'vkIOS';
					@theme-inherits-from: 'vkIOS';
					@colors-scheme: dark;
					@color-background: #FFF;
					@color-background--hover: #AAA;
					@color-background--active: #CCC;
				`,
				styl: stripIndent`
					$theme-name = 'vkIOSDark';
					$theme-name-base = 'vkIOS';
					$theme-inherits-from = 'vkIOS';
					$colors-scheme = dark;
					$color-background = #FFF;
					$color-background--hover = #AAA;
					$color-background--active = #CCC;
				`,
			},
		});
	});
});
Example #14
Source File: compileBreakpointsCssVarsDeclaration.test.ts    From vkui-tokens with MIT License 4 votes vote down vote up
describe('compileBreakpointsCssVarsDeclaration', () => {
	it('should not work without breakpoints', () => {
		const theme = {};
		expect(
			compileBreakpointsCssVarsDeclaration(theme as ThemeCssVarsWide),
		).toBe(null);
	});

	it('should work with breakpoints and empty vals', () => {
		const theme: Partial<ParadigmThemeCssVarsWide> = {
			breakpoints: {
				touch: {
					breakpoint: 0,
					adaptiveValue: 'compactX',
				},
				desktopS: {
					breakpoint: 768,
					adaptiveValue: 'regular',
				},
			},
		};
		expect(
			compileBreakpointsCssVarsDeclaration(theme as ThemeCssVarsWide),
		).toBe(null);
	});

	it('should work with non adaptive values', () => {
		const theme: Partial<ParadigmThemeCssVarsWide> = {
			breakpoints: {
				touch: {
					breakpoint: 0,
					adaptiveValue: 'compactX',
				},
				desktopS: {
					breakpoint: 768,
					adaptiveValue: 'regular',
				},
			},
			x1: {
				name: '--vkui--x1',
				value: 'var(--vkui--x1, 4px)',
				originalValue: '4px',
			},
		};
		expect(
			compileBreakpointsCssVarsDeclaration(theme as ThemeCssVarsWide),
		).toBe(null);
	});

	it('should work with flat adaptive values and several breakpotins', () => {
		const theme: Partial<ParadigmThemeCssVarsWide> = {
			breakpoints: {
				touch: {
					breakpoint: 0,
					adaptiveValue: 'compact',
				},
				desktopS: {
					breakpoint: 768,
					adaptiveValue: 'regular',
				},
			},
			sizePopupBasePadding: {
				auto: {
					name: '--vkui--size_popup_base_padding',
					value: 'var(--vkui--size_popup_base_padding)',
				},
				compact: {
					name: '--vkui--size_popup_base_padding--compact',
					value:
						'var(--vkui--size_popup_base_padding--compact, 16px)',
					originalValue: '16px',
				},
				regular: {
					name: '--vkui--size_popup_base_padding--regular',
					value:
						'var(--vkui--size_popup_base_padding--regular, 20px)',
					originalValue: '20px',
				},
			},
		};
		expect(compileBreakpointsCssVarsDeclaration(theme as ThemeCssVarsWide))
			.toBe(stripIndent`
			:root {
				--vkui--size_popup_base_padding: var(--vkui--size_popup_base_padding--regular);
			}

			@media (max-width: 767px) {
				:root, .vkui--force-auto {
					--vkui--size_popup_base_padding: var(--vkui--size_popup_base_padding--compact);
				}
			}

			.vkui--force-touch {
				--vkui--size_popup_base_padding: var(--vkui--size_popup_base_padding--compact);
			}

			@media (min-width: 768px) {
				:root, .vkui--force-auto {
					--vkui--size_popup_base_padding: var(--vkui--size_popup_base_padding--regular);
				}
			}

			.vkui--force-desktop_s {
				--vkui--size_popup_base_padding: var(--vkui--size_popup_base_padding--regular);
			}
			`);
	});

	it('should work with flat adaptive values and several breakpotins and without overriding', () => {
		const theme: Partial<ParadigmThemeCssVarsWide> = {
			breakpoints: {
				touch: {
					breakpoint: 0,
					adaptiveValue: 'compact',
				},
				desktopS: {
					breakpoint: 768,
					adaptiveValue: 'regular',
				},
			},
			sizePopupBasePadding: {
				auto: {
					name: '--vkui--size_popup_base_padding',
					value: 'var(--vkui--size_popup_base_padding)',
				},
				regular: {
					name: '--vkui--size_popup_base_padding--regular',
					value:
						'var(--vkui--size_popup_base_padding--regular, 20px)',
					originalValue: '20px',
				},
			},
		};
		expect(compileBreakpointsCssVarsDeclaration(theme as ThemeCssVarsWide))
			.toBe(stripIndent`
			:root {
				--vkui--size_popup_base_padding: 20px;
			}
			`);
	});

	it('should work with adaptive complex object', () => {
		const theme: Partial<ParadigmThemeCssVarsWide> = {
			breakpoints: {
				touch: {
					breakpoint: 0,
					adaptiveValue: 'compact',
				},
				desktopS: {
					breakpoint: 768,
					adaptiveValue: 'regular',
				},
			},
			fontH1: {
				auto: {
					fontSize: {
						name: '--vkui--font_h1--font_size',
						value: 'var(--vkui--font_h1--font_size)',
					},
					lineHeight: {
						name: '--vkui--font_h1--line_height',
						value: 'var(--vkui--font_h1--line_height)',
					},
				} as any,
				compact: {
					fontSize: {
						name: '--vkui--font_h1--font_size--compact',
						value: 'var(--vkui--font_h1--font_size--compact, 24px)',
						originalValue: '24px',
					},
				},
				regular: {
					fontSize: {
						name: '--vkui--font_h1--font_size--regular',
						value: 'var(--vkui--font_h1--font_size--regular, 22px)',
						originalValue: '22px',
					},
					lineHeight: {
						name: '--vkui--font_h1--line_height--regular',
						value:
							'var(--vkui--font_h1--line_height--regular, 30px)',
						originalValue: '30px',
					},
				} as any,
			},
		};

		expect(compileBreakpointsCssVarsDeclaration(theme as ThemeCssVarsWide))
			.toBe(stripIndent`
			:root {
				--vkui--font_h1--font_size: var(--vkui--font_h1--font_size--regular);
				--vkui--font_h1--line_height: var(--vkui--font_h1--line_height--regular);
			}

			@media (max-width: 767px) {
				:root, .vkui--force-auto {
					--vkui--font_h1--font_size: var(--vkui--font_h1--font_size--compact);
				}
			}

			.vkui--force-touch {
				--vkui--font_h1--font_size: var(--vkui--font_h1--font_size--compact);
			}

			@media (min-width: 768px) {
				:root, .vkui--force-auto {
					--vkui--font_h1--font_size: var(--vkui--font_h1--font_size--regular);
				}
			}

			.vkui--force-desktop_s {
				--vkui--font_h1--font_size: var(--vkui--font_h1--font_size--regular);
			}
			`);
	});
});
Example #15
Source File: generateOperationId.ts    From amplify-codegen with Apache License 2.0 4 votes vote down vote up
describe(`generateOperationId()`, () => {
  it(`should generate different operation IDs for different operations`, () => {
    const context1 = compile(`
      query Hero {
        hero {
          ...HeroDetails
        }
      }
      fragment HeroDetails on Character {
        name
      }`);

    const { operationId: id1 } = generateOperationId(context1.operations['Hero'], context1.fragments);

    const context2 = compile(`
      query Hero {
        hero {
          ...HeroDetails
        }
      }
      fragment HeroDetails on Character {
        appearsIn
      }`);

    const { operationId: id2 } = generateOperationId(context2.operations['Hero'], context2.fragments);

    expect(id1).not.toBe(id2);
  });

  it(`should generate the same operation ID regardless of operation formatting/commenting`, () => {
    const context1 = compile(`
      query HeroName($episode: Episode) {
        hero(episode: $episode) {
          name
        }
      }`);

    const { operationId: id1 } = generateOperationId(context1.operations['HeroName'], context1.fragments);

    const context2 = compile(`
      # Profound comment
      query HeroName($episode:Episode) { hero(episode: $episode) { name } }
      # Deeply meaningful comment`);

    const { operationId: id2 } = generateOperationId(context2.operations['HeroName'], context2.fragments);

    expect(id1).toBe(id2);
  });

  it(`should generate the same operation ID regardless of fragment order`, () => {
    const context1 = compile(`
      query Hero {
        hero {
          ...HeroName
          ...HeroAppearsIn
        }
      }
      fragment HeroName on Character {
        name
      }
      fragment HeroAppearsIn on Character {
        appearsIn
      }`);

    const { operationId: id1 } = generateOperationId(context1.operations['Hero'], context1.fragments);

    const context2 = compile(`
      query Hero {
        hero {
          ...HeroName
          ...HeroAppearsIn
        }
      }
      fragment HeroAppearsIn on Character {
        appearsIn
      }
      fragment HeroName on Character {
        name
      }`);

    const { operationId: id2 } = generateOperationId(context2.operations['Hero'], context2.fragments);

    expect(id1).toBe(id2);
  });

  it(`should generate appropriate operation ID mapping source when there are nested fragment references`, () => {
    const context = compile(`
      query Hero {
        hero {
          ...HeroDetails
        }
      }
      fragment HeroName on Character {
        name
      }
      fragment HeroDetails on Character {
        ...HeroName
        appearsIn
      }`);

    const { sourceWithFragments } = generateOperationId(context.operations['Hero'], context.fragments);

    expect(sourceWithFragments).toBe(stripIndent`
      query Hero {
        hero {
          ...HeroDetails
        }
      }
      fragment HeroDetails on Character {
        ...HeroName
        appearsIn
      }
      fragment HeroName on Character {
        name
      }`);
  });
});
Example #16
Source File: language.ts    From amplify-codegen with Apache License 2.0 4 votes vote down vote up
describe('Swift code generation: Basic language constructs', () => {
  let generator: SwiftGenerator<any>;

  beforeEach(() => {
    generator = new SwiftGenerator({});
  });

  it(`should generate a class declaration`, () => {
    generator.classDeclaration({ className: 'Hero', modifiers: ['public', 'final'] }, () => {
      generator.propertyDeclaration({ propertyName: 'name', typeName: 'String' });
      generator.propertyDeclaration({ propertyName: 'age', typeName: 'Int' });
    });

    expect(generator.output).toBe(stripIndent`
      public final class Hero {
        public var name: String
        public var age: Int
      }`);
  });

  it(`should generate a struct declaration`, () => {
    generator.structDeclaration({ structName: 'Hero' }, () => {
      generator.propertyDeclaration({ propertyName: 'name', typeName: 'String' });
      generator.propertyDeclaration({ propertyName: 'age', typeName: 'Int' });
    });

    expect(generator.output).toBe(stripIndent`
      public struct Hero {
        public var name: String
        public var age: Int
      }`);
  });

  it(`should generate an escaped struct declaration`, () => {
    generator.structDeclaration({ structName: 'Type' }, () => {
      generator.propertyDeclaration({ propertyName: 'name', typeName: 'String' });
      generator.propertyDeclaration({ propertyName: 'yearOfBirth', typeName: 'Int' });
    });

    expect(generator.output).toBe(stripIndent`
      public struct \`Type\` {
        public var name: String
        public var yearOfBirth: Int
      }`);
  });

  it(`should generate nested struct declarations`, () => {
    generator.structDeclaration({ structName: 'Hero' }, () => {
      generator.propertyDeclaration({ propertyName: 'name', typeName: 'String' });
      generator.propertyDeclaration({ propertyName: 'friends', typeName: '[Friend]' });

      generator.structDeclaration({ structName: 'Friend' }, () => {
        generator.propertyDeclaration({ propertyName: 'name', typeName: 'String' });
      });
    });

    expect(generator.output).toBe(stripIndent`
      public struct Hero {
        public var name: String
        public var friends: [Friend]

        public struct Friend {
          public var name: String
        }
      }`);
  });

  it(`should generate a protocol declaration`, () => {
    generator.protocolDeclaration({ protocolName: 'HeroDetails', adoptedProtocols: ['HasName'] }, () => {
      generator.protocolPropertyDeclaration({ propertyName: 'name', typeName: 'String' });
      generator.protocolPropertyDeclaration({ propertyName: 'age', typeName: 'Int' });
    });

    expect(generator.output).toBe(stripIndent`
      public protocol HeroDetails: HasName {
        var name: String { get }
        var age: Int { get }
      }`);
  });

  it(`should handle multi-line descriptions`, () => {
    generator.structDeclaration({ structName: 'Hero', description: 'A hero' }, () => {
      generator.propertyDeclaration({
        propertyName: 'name',
        typeName: 'String',
        description: `A multiline comment \n on the hero's name.`,
      });
      generator.propertyDeclaration({ propertyName: 'age', typeName: 'String', description: `A multiline comment \n on the hero's age.` });
    });

    expect(generator.output).toMatchSnapshot();
  });
});
Example #17
Source File: compileGetDeclarationString.test.ts    From vkui-tokens with MIT License 4 votes vote down vote up
describe('compileGetDeclarationString', () => {
	it('should work with empty', () => {
		const theme = {};
		expect(compileGetDeclarationString(theme as ThemeCssVarsWide)).toBe(
			stripIndent`
			import {Properties} from 'csstype';

			export function getDeclarationVarString(): string {
				return \`\`;
			}

			export function getDeclarationVarObject(): Properties {
				return {} as Properties;
			}
			`,
		);
	});

	it('should work with any values', () => {
		const theme: Pick<
			ParadigmThemeCssVarsWide,
			'x1' | 'sizePopupBasePadding' | 'colorTextAccent'
		> = {
			x1: {
				name: '--paradigm--x1',
				value: 'val(--paradigm--x1, 4px)',
				originalValue: '4px',
			},

			sizePopupBasePadding: {
				auto: {
					name: '--vkui--size_popup_base_padding',
					value: 'var(--vkui--size_popup_base_padding)',
				},
				compact: {
					name: '--vkui--size_popup_base_padding--compact',
					value:
						'var(--vkui--size_popup_base_padding--compact, 16px)',
					originalValue: '16px',
				},
				regular: {
					name: '--vkui--size_popup_base_padding--regular',
					value:
						'var(--vkui--size_popup_base_padding--regular, 20px)',
					originalValue: '20px',
				},
			},

			colorTextAccent: {
				normal: {
					name: '--vkui--color_text_accent',
					value: 'val(--vkui--color_text_accent, white)',
					originalValue: 'white',
				},
				hover: {
					name: '--vkui--color_text_accent--hover',
					value: 'val(--vkui--color_text_accent--hover, black)',
					originalValue: 'black',
				},
				active: {
					name: '--vkui--color_text_accent--active',
					value: 'val(--vkui--color_text_accent--active, red)',
					originalValue: 'red',
				},
			},
		};

		expect(
			compileGetDeclarationString(theme as ParadigmThemeCssVarsWide),
		).toBe(
			stripIndent`
			import {Properties} from 'csstype';

			export function getDeclarationVarString(): string {
				return \`--paradigm--x1: 4px;--vkui--size_popup_base_padding--compact: 16px;--vkui--size_popup_base_padding--regular: 20px;--vkui--color_text_accent: white;--vkui--color_text_accent--hover: black;--vkui--color_text_accent--active: red;\`;
			}

			export function getDeclarationVarObject(): Properties {
				return {"--paradigm--x1":"4px","--vkui--size_popup_base_padding--compact":"16px","--vkui--size_popup_base_padding--regular":"20px","--vkui--color_text_accent":"white","--vkui--color_text_accent--hover":"black","--vkui--color_text_accent--active":"red"} as Properties;
			}
			`,
		);
	});

	it('should work onlyColorsMode', () => {
		const theme: Pick<
			ParadigmThemeCssVarsWide,
			'x1' | 'sizePopupBasePadding' | 'colorTextAccent'
		> = {
			x1: {
				name: '--paradigm--x1',
				value: 'val(--paradigm--x1, 4px)',
				originalValue: '4px',
			},

			sizePopupBasePadding: {
				auto: {
					name: '--vkui--size_popup_base_padding',
					value: 'var(--vkui--size_popup_base_padding)',
				},
				compact: {
					name: '--vkui--size_popup_base_padding--compact',
					value:
						'var(--vkui--size_popup_base_padding--compact, 16px)',
					originalValue: '16px',
				},
				regular: {
					name: '--vkui--size_popup_base_padding--regular',
					value:
						'var(--vkui--size_popup_base_padding--regular, 20px)',
					originalValue: '20px',
				},
			},

			colorTextAccent: {
				normal: {
					name: '--vkui--color_text_accent',
					value: 'val(--vkui--color_text_accent, white)',
					originalValue: 'white',
				},
				hover: {
					name: '--vkui--color_text_accent--hover',
					value: 'val(--vkui--color_text_accent--hover, black)',
					originalValue: 'black',
				},
				active: {
					name: '--vkui--color_text_accent--active',
					value: 'val(--vkui--color_text_accent--active, red)',
					originalValue: 'red',
				},
			},
		};

		expect(
			compileGetDeclarationString(
				theme as ParadigmThemeCssVarsWide,
				'onlyColors',
			),
		).toBe(
			stripIndent`
			import {Properties} from 'csstype';

			export function getDeclarationVarColorsString(): string {
				return \`--vkui--color_text_accent: white;--vkui--color_text_accent--hover: black;--vkui--color_text_accent--active: red;\`;
			}

			export function getDeclarationVarColorsObject(): Properties {
				return {"--vkui--color_text_accent":"white","--vkui--color_text_accent--hover":"black","--vkui--color_text_accent--active":"red"} as Properties;
			}
			`,
		);
	});
});
Example #18
Source File: CodeExample.tsx    From hacker-ui with MIT License 4 votes vote down vote up
function CodeExample(props: Props) {
  const {
    Root,
    styles,
    children,
    javascriptCodePromise,
    typescriptCodePromise,
  } = useStyles(props, 'section');
  const theme = useTheme();
  const [codeExampleOpen, setCodeExampleOpen] = useState(false);
  const [codeType, setCodeType] = useState<'typescript' | 'javascript'>(
    'typescript',
  );

  const [typescriptCode, setTypescriptCode] = useState('Loading…');
  const [javascriptCode, setJavascriptCode] = useState('Loading…');

  const code = codeType === 'typescript' ? typescriptCode : javascriptCode;

  useEffect(() => {
    javascriptCodePromise.then((mod: any) => setJavascriptCode(mod.default));
  }, [javascriptCodePromise]);

  useEffect(() => {
    typescriptCodePromise.then((mod: any) => setTypescriptCode(mod.default));
  }, [typescriptCodePromise]);

  const handleCopy = () => {
    alert('Code copied to clipboard!');
  };

  const codeSandboxUrl = useMemo(() => {
    const parameters = getParameters({
      files: {
        [`Example.${codeType === 'typescript' ? 'tsx' : 'js'}`]: {
          content: code,
          isBinary: false,
        },
        [`index.${codeType === 'typescript' ? 'tsx' : 'js'}`]: {
          content: stripIndent`
            import React from 'react';
            import { render } from 'react-dom';
            import { ThemeProvider } from 'hacker-ui';
            import Example from './Example';
            import theme from './theme';
            import 'normalize.css';
            import './index.css';
            
            const container = document.createElement('div');
            container.style.position = 'fixed';
            container.style.top = '0';
            container.style.left = '0';
            container.style.bottom = '0';
            container.style.right = '0';
            container.style.width = '100vw';
            container.style.height = '100vh';
            container.style.padding = '16px';
            
            document.body.appendChild(container);
            
            function App() {
              return (
                <ThemeProvider theme={theme}>
                  <Example />
                </ThemeProvider>
              );
            }
            
            render(<App />, container);
          `,
          isBinary: false,
        },
        [`theme.${codeType === 'typescript' ? 'tsx' : 'js'}`]: {
          content: stripIndent`
            import { createTheme } from 'hacker-ui';

            const theme = createTheme({
              /* add your overrides here */
            });

            ${
              codeType === 'typescript'
                ? 'export type Theme = typeof theme;'
                : ''
            }
            
            export default theme;
          `,
          isBinary: false,
        },
        'package.json': {
          content: JSON.stringify(
            {
              name: 'react',
              version: '1.0.0',
              description: '',
              keywords: [],
              main: `src/index.${codeType === 'typescript' ? 'tsx' : 'js'}`,
              dependencies: {
                'hacker-ui': '0.0.0-88cd8a409',
                react: '16.12.0',
                'react-dom': '16.12.0',
                'react-scripts': '3.0.1',
                '@fortawesome/fontawesome-svg-core': '^1.2.26',
                '@fortawesome/free-brands-svg-icons': '^5.12.1',
                '@fortawesome/free-solid-svg-icons': '^5.12.0',
                '@fortawesome/react-fontawesome': '^0.1.8',
                'normalize.css': '^8.0.1',
              },
              devDependencies: {
                '@types/react': '16.9.19',
                '@types/react-dom': '16.9.5',
                typescript: '3.3.3',
              },
              scripts: {
                start: 'react-scripts start',
                build: 'react-scripts build',
                test: 'react-scripts test --env=jsdom',
                eject: 'react-scripts eject',
              },
              browserslist: [
                '>0.2%',
                'not dead',
                'not ie <= 11',
                'not op_mini all',
              ],
            },
            null,
            2,
          ),
          isBinary: false,
        },
        '.prettier.rc': {
          content: JSON.stringify(
            {
              printWidth: 80,
              singleQuote: true,
              trailingComma: 'all',
            },
            null,
            2,
          ),
          isBinary: false,
        },
        'index.css': {
          content: stripIndent`
            body {
              font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica,
                Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol';
            }
            
            :root {
              font-size: 16px;
            }
            
            * {
              box-sizing: border-box;
            }
          `,
          isBinary: false,
        },
        'augments.d.ts': {
          content: stripIndent`
            import {
              StyleFnArgs,
              ReactComponent,
              StyleProps,
              GetComponentProps,
            } from 'react-style-system';
            
            declare module 'react-style-system' {
              type Theme = typeof import('./theme').default;

              // provides an override type that includes the type for your theme
              export function useTheme(): Theme;
            
              // provides an override type that includes the type for your theme
              export function createStyles<Styles, ComponentType extends ReactComponent>(
                stylesFn: (args: StyleFnArgs<Theme>) => Styles,
              ): <Props extends StyleProps<Styles>>(
                props: Props,
                component?: ComponentType,
              ) => {
                Root: React.ComponentType<GetComponentProps<ComponentType>>;
                styles: { [P in keyof Styles]: string } & {
                  cssVariableObject: { [key: string]: string };
                };
              } & Omit<Props, keyof StyleProps<any>>;
            }
          `,
          isBinary: false,
        },
        ...(codeType === 'typescript'
          ? {
              'tsconfig.json': {
                content: JSON.stringify(
                  {
                    include: ['./src/*'],
                    compilerOptions: {
                      strict: true,
                      lib: ['dom', 'es2015'],
                      jsx: 'react',
                    },
                  },
                  null,
                  2,
                ),
                isBinary: false,
              },
            }
          : null),
      },
    });

    return `https://codesandbox.io/api/v1/sandboxes/define?parameters=${parameters}`;
  }, [code, codeType]);

  useEffect(() => {
    if (!codeExampleOpen) return;

    setTimeout(() => {
      const { Prism } = window as any;
      if (!Prism) return;
      Prism.highlightAll();
    }, 250);
  }, [codeExampleOpen, codeType]);

  return (
    <>
      <Root>
        <Tooltip title="Show code">
          {(props) => (
            <Button
              aria-label="Show code"
              shape="icon"
              className={styles.codeButton}
              color={theme.bland}
              onClick={() => setCodeExampleOpen(true)}
              {...props}
            >
              <FontAwesomeIcon icon={faCode} />
            </Button>
          )}
        </Tooltip>
        {children}
      </Root>

      <Modal
        style={styles.cssVariableObject}
        open={codeExampleOpen}
        onClose={() => setCodeExampleOpen(false)}
      >
        <ModalHeader className={styles.modalHeader}>
          <RadioGroup
            className={styles.modalButtons}
            value={codeType}
            onChange={(e) => setCodeType(e.currentTarget.value as any)}
          >
            <FormControl className={styles.choice}>
              <Radio className={styles.radio} value="typescript" />
              <Label>TypeScript</Label>
            </FormControl>

            <FormControl className={styles.choice}>
              <Radio className={styles.radio} value="javascript" />
              <Label>JavaScript</Label>
            </FormControl>
          </RadioGroup>
        </ModalHeader>

        <ModalContent>
          <div className={styles.floatingButtons}>
            <Tooltip title="Open in CodeSandbox">
              {(props) => (
                <Button
                  component="a"
                  // the props API for `Button` and `a` don't match so we
                  // use `@ts-ignore` to get around it for this issue
                  // @ts-ignore
                  href={codeSandboxUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  shape="icon"
                  color="white"
                  surface="black"
                  size="large"
                  variant="filled"
                  {...props}
                >
                  <CodeSandboxIcon />
                </Button>
              )}
            </Tooltip>

            <Tooltip title="Copy code">
              {(props) => (
                <CopyToClipBoard text={code} onCopy={handleCopy}>
                  <Button
                    shape="icon"
                    color="white"
                    surface="black"
                    size="large"
                    variant="filled"
                    {...props}
                  >
                    <FontAwesomeIcon icon={faCopy} size="lg" />
                  </Button>
                </CopyToClipBoard>
              )}
            </Tooltip>
          </div>

          <div className={styles.codeContainer}>
            <pre
              className={classNames(styles.code, {
                'language-tsx': codeType === 'typescript',
                'language-jsx': codeType === 'javascript',
              })}
            >
              <code>{code}</code>
            </pre>
          </div>
        </ModalContent>

        <ModalFooter>
          <ModalActions>
            <Button
              color={theme.bland}
              onClick={() => setCodeExampleOpen(false)}
            >
              Close
            </Button>
          </ModalActions>
        </ModalFooter>
      </Modal>
    </>
  );
}
Example #19
Source File: compileBreakpointsCssVarsDeclaration.ts    From vkui-tokens with MIT License 4 votes vote down vote up
/**
 * Компилирует медиаквери переходы между переменными
 * @param sourceTheme
 * @param type
 */
// eslint-disable-next-line sonarjs/cognitive-complexity
export function compileBreakpointsCssVarsDeclaration<T = Theme>(
	sourceTheme: ThemeCssVarsWide<T, Extract<keyof T, 'breakpoints'>>,
	type: DeclarationType = 'default',
): string | null {
	if (!('breakpoints' in sourceTheme)) {
		return null;
	}
	const breakpoints = sourceTheme['breakpoints'];
	const customMedia = processCustomMedia(sourceTheme as any);

	const theme: ThemeCssVarsWide<T> =
		type === 'onlyColors' ? getOnlyColors(sourceTheme) : sourceTheme;

	const {adaptiveValues} = accumulateValues<any>({
		theme,
	});

	let result = '';

	if (!Object.keys(adaptiveValues.auto).length) {
		return null;
	}

	result += stripIndent`
	:root {
${getVarString({valuesObject: adaptiveValues.auto, prefix: '\t\t'})}
	}`;

	const adaptivityStatesLength = Object.keys(adaptiveValues).length;

	// только regular и auto
	if (adaptivityStatesLength === 2) {
		return result;
	}

	let regularValues = '';
	let mediaValues = '';

	Object.entries(adaptiveValues)
		.sort(([a]) => (a === 'regular' ? 1 : -1))
		.forEach(([adaptivityState, valuesObject]) => {
			const isRegular = adaptivityState === 'regular';

			if (adaptivityState === 'auto') {
				return;
			}

			const usedViewport = findViewportByAdaptivityState(
				breakpoints,
				adaptivityState as keyof Adaptive<any>,
			);

			mediaValues += stripIndent`
			@media ${customMedia[`width${capitalize(usedViewport)}`]} {
				:root, .vkui--force-auto {
					${stripIndents(
						isRegular
							? regularValues
							: getVarString({
									valuesObject,
									prefix: '',
									callback: (name) => {
										if (isRegular) {
											return;
										}

										const regularName = name.replace(
											new RegExp(`${adaptivityState}$`),
											'regular',
										);
										const regularValue =
											adaptiveValues.regular[regularName];
										if (regularValue) {
											regularValues += `${regularName}: ${regularValue};\n`;
										}
									},
							  }),
					)}
				}
			}

			.vkui--force-${convertCamelToSnake(usedViewport)} {
				${stripIndents(
					isRegular
						? regularValues
						: getVarString({
								valuesObject,
								prefix: '',
						  }),
				)}
			}
			`;

			mediaValues += '\n\n';
		});

	return stripIndent(`${result}\n\n${mediaValues}`);
}