Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 92 additions & 0 deletions apps/automated/src/fonts/SNPro-OFL.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
Copyright 2024 The SN Pro Project Authors (https://github.com/supernotes/sn-pro)

This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://openfontlicense.org

-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------

PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.

The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.

DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.

"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).

"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).

"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.

"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.

PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:

1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.

2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.

3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.

4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.

5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.

TERMINATION
This license becomes null and void if any of the above conditions are
not met.

DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
3 changes: 3 additions & 0 deletions apps/automated/src/fonts/SNPro.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
SN Pro's upright variable font has a `wght` range of 200–900 and a default of 200. The variable-font tests use it to distinguish normal CSS weight 400 from the font's default instance.

Source: https://github.com/supernotes/sn-pro/tree/e025ac4755352167a4b160bfb77c72068b04b55c/fonts/variable (`SNPro[wght].ttf`). License: `SNPro-OFL.txt`. SHA-256: `63abf11c85df08dde6cec421c133c723408ee1e5744bb280b660dfd8be3fe061`.
Binary file added apps/automated/src/fonts/SNPro.ttf
Binary file not shown.
5 changes: 5 additions & 0 deletions apps/automated/src/test-runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,11 @@ allTests['VIEW-LAYOUT-EVENT'] = viewLayoutChangedEventTests;
import * as styleTests from './ui/styling/style-tests';
allTests['STYLE'] = styleTests;

import * as variableFontTests from './ui/styling/variable-font-tests';
if (__APPLE__) {
allTests['VARIABLE-FONT'] = variableFontTests;
}

import * as visualStateTests from './ui/styling/visual-state-tests';
allTests['VISUAL-STATE'] = visualStateTests;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export {};
3 changes: 3 additions & 0 deletions apps/automated/src/ui/styling/variable-font-tests.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function test_variable_font_default_and_computed_weights(): void;
export function test_variable_font_inheritance_and_retained_updates(): void;
export function test_variable_font_explicit_axis_precedence_and_removal(): void;
125 changes: 125 additions & 0 deletions apps/automated/src/ui/styling/variable-font-tests.ios.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import { Label, TextField, TextView, StackLayout } from '@nativescript/core';
import { Font } from '@nativescript/core/ui/styling/font';
import * as TKUnit from '../../tk-unit';
import * as helper from '../../ui-helper';

type TextControl = Label | TextField | TextView;

const css = `
Label, TextField, TextView { font-family: 'SN Pro'; font-size: 24; }
.medium { font-weight: 500; }
.semibold { font-weight: 600; }
.bold { font-weight: 700; }
`;

function coordinate(font: UIFont): number | undefined {
const axes = CTFontCopyVariationAxes(font);
for (let index = 0; index < (axes?.count ?? 0); index++) {
const axis: NSDictionary<string, unknown> = axes.objectAtIndex(index);
if (Number(axis.objectForKey(kCTFontVariationAxisIdentifierKey)) === 0x77676874) {
return Number(CTFontCopyVariation(font)?.objectForKey(0x77676874) ?? axis.objectForKey(kCTFontVariationAxisDefaultValueKey));
}
}
return undefined;
}

function nativeFont(control: TextControl): UIFont {
const native: UILabel | UITextField | UITextView = control.ios;
return native.font;
}

function assertWeight(controls: TextControl[], expected: number) {
for (const control of controls) {
const font = nativeFont(control);
TKUnit.assertEqual(font.familyName, 'SN Pro');
TKUnit.assertAreClose(coordinate(font), expected, 0.5, control.typeName + ' weight');
TKUnit.assertAreClose(font.pointSize, 24, 0.5);
}
}

function withControls(test: (controls: TextControl[], parent: StackLayout) => void) {
const parent = new StackLayout();
const controls: TextControl[] = [new Label(), new TextField(), new TextView()];
for (const control of controls) {
control.text = 'Variable font weight';
parent.addChild(control);
}
helper.buildUIAndRunTest(parent, () => test(controls, parent), { pageCss: css });
}

export function test_variable_font_default_and_computed_weights() {
withControls((controls) => {
// SN Pro defaults to 200; normal CSS must still select 400.
assertWeight(controls, 400);
for (const [className, expected] of [
['medium', 500],
['semibold', 600],
['bold', 700],
] as const) {
for (const control of controls) {
control.className = className;
}
assertWeight(controls, expected);
}
for (const control of controls) {
control.fontWeight = '100';
}
assertWeight(controls, 200);
});
}

export function test_variable_font_inheritance_and_retained_updates() {
withControls((controls, parent) => {
const natives = controls.map((control) => control.ios);
parent.className = 'bold';
for (const control of controls) {
control.className = 'semibold';
}
assertWeight(controls, 600);
for (const control of controls) {
control.className = 'medium';
}
assertWeight(controls, 500);
for (const control of controls) {
control.className = '';
}
assertWeight(controls, 700);
parent.className = '';
assertWeight(controls, 400);
for (const control of controls) {
control.fontFamily = 'Courier';
TKUnit.assertEqual(nativeFont(control).familyName, 'Courier');
TKUnit.assertEqual(coordinate(nativeFont(control)), undefined);
control.fontFamily = 'SN Pro';
}
assertWeight(controls, 400);
controls.forEach((control, index) => TKUnit.assertEqual(control.ios, natives[index]));
});
}

export function test_variable_font_explicit_axis_precedence_and_removal() {
withControls((controls) => {
for (const control of controls) {
control.className = 'bold';
control.style.fontVariationSettings = [{ axis: 'wght', value: 550 }];
}
assertWeight(controls, 550);
for (const control of controls) {
control.className = 'medium';
}
assertWeight(controls, 550);
for (const control of controls) {
control.style.fontVariationSettings = null;
}
assertWeight(controls, 500);
});

const font = new Font('SN Pro', 24, 'normal', '700', 1.5, [{ axis: 'wght', value: 550 }]);
const resolved = font.getUIFont(UIFont.systemFontOfSize(17));
TKUnit.assertAreClose(coordinate(resolved), 550, 0.5);
TKUnit.assertAreClose(resolved.pointSize, 36, 0.5);
TKUnit.assertEqual(font.fontVariationSettings.length, 1);
const derived = font.withFontVariationSettings(null);
TKUnit.assertAreClose(coordinate(derived.getUIFont(UIFont.systemFontOfSize(17))), 700, 0.5);
TKUnit.assertNull(derived.fontVariationSettings);
}
70 changes: 45 additions & 25 deletions packages/core/ui/styling/font.ios.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,18 @@ interface FontDescriptor {
fontFamily: string[];
fontSize: number;
fontWeight: number;
cssFontWeight: number;
fontVariationSettings: Array<FontVariationSettingsType> | null;
isBold: boolean;
isItalic: boolean;
}

type FontVariationAxisType = 'kCGFontVariationAxisDefaultValue' | 'kCGFontVariationAxisMaxValue' | 'kCGFontVariationAxisMinValue' | 'kCGFontVariationAxisName';

const uiFontCache = new Map<string, UIFont>();

function computeFontCacheKey(fontDescriptor: FontDescriptor) {
const { fontFamily, fontSize, fontWeight, fontVariationSettings, isBold, isItalic } = fontDescriptor;
const { fontFamily, fontSize, fontWeight, cssFontWeight, fontVariationSettings, isBold, isItalic } = fontDescriptor;
const sep = ':';
return [fontFamily.join(sep), fontSize, fontWeight, String(FontVariationSettings.toString(fontVariationSettings)).replace(/'/g, '').replace(/[\s,]/g, '_'), isBold, isItalic].join(sep);
return [fontFamily.join(sep), fontSize, fontWeight, cssFontWeight, String(FontVariationSettings.toString(fontVariationSettings)).replace(/'/g, '').replace(/[\s,]/g, '_'), isBold, isItalic].join(sep);
}

function getUIFontCached(fontDescriptor: FontDescriptor) {
Expand All @@ -33,28 +32,37 @@ function getUIFontCached(fontDescriptor: FontDescriptor) {
return uiFontCache.get(cacheKey);
}
let uiFont = NativeScriptUtils.createUIFont(fontDescriptor as any);
if (fontDescriptor.fontVariationSettings?.length) {
let font = CGFontCreateWithFontName(uiFont.fontName);
const variationAxes: NSArray<NSDictionary<FontVariationAxisType, string | number>> = CGFontCopyVariationAxes(font);
// This can be null if font doesn't support axes
if (variationAxes?.count) {
const variationSettings = NSMutableDictionary.new();
const variationAxesCount = variationAxes.count;
const variationAxesNames: string[] = [];

for (let i = 0, length = variationAxes.count; i < length; i++) {
variationAxesNames.push(String(variationAxes[i].objectForKey('kCGFontVariationAxisName')));
}

for (const variationSetting of fontDescriptor.fontVariationSettings) {
const axisName = fuzzySearch(variationSetting.axis, variationAxesNames);
if (axisName?.length) {
variationSettings.setValueForKey(variationSetting.value, axisName[0]);
}
// Derive coordinates after CSS resolution without mutating inherited settings.
const axes: NSArray<NSDictionary<string, string | number>> = CTFontCopyVariationAxes(uiFont);
if (axes?.count) {
const variations = NSMutableDictionary.new<number, number>();
const current = CTFontCopyVariation(uiFont);
if (current) {
variations.addEntriesFromDictionary(current);
}
let changed = false;
const settings = fontDescriptor.fontVariationSettings || [];
for (let index = 0; index < axes.count; index++) {
const axis = axes.objectAtIndex(index);
const identifier = Number(axis.objectForKey(kCTFontVariationAxisIdentifierKey));
const tag = String.fromCharCode(identifier >>> 24, (identifier >>> 16) & 255, (identifier >>> 8) & 255, identifier & 255);
const name = String(axis.objectForKey(kCTFontVariationAxisNameKey));
const explicit = settings.find((setting) => setting.axis.toLowerCase() === tag.toLowerCase()) || settings.find((setting) => fuzzySearch(setting.axis, [name]).length > 0);
const value = explicit ? explicit.value : tag === 'wght' ? fontDescriptor.cssFontWeight : undefined;
if (value === undefined) {
continue;
}

font = CGFontCreateCopyWithVariations(font, variationSettings);
uiFont = CTFontCreateWithGraphicsFont(font, fontDescriptor.fontSize, null, null);
const minimum = Number(axis.objectForKey(kCTFontVariationAxisMinimumValueKey));
const maximum = Number(axis.objectForKey(kCTFontVariationAxisMaximumValueKey));
variations.setObjectForKey(Math.max(minimum, Math.min(maximum, value)), identifier);
changed = true;
}
if (changed) {
// Copy the resolved font to preserve other coordinates and italic traits.
const attributes = NSMutableDictionary.new<string, NSDictionary<number, number>>();
attributes.setObjectForKey(variations, kCTFontVariationAttribute);
const descriptor = UIFontDescriptor.fontDescriptorWithFontAttributes(attributes);
uiFont = CTFontCreateCopyWithAttributes(uiFont, fontDescriptor.fontSize, null, descriptor);
}
}

Expand Down Expand Up @@ -103,6 +111,7 @@ export class Font extends FontBase {
// Apply a11y scale and calculate proper font size (avoid applying multiplier to native point size as it's messing calculations)
fontSize: this.fontSize ? this.fontSize * this.fontScale : defaultFont.pointSize,
fontWeight: getNativeFontWeight(this.fontWeight),
cssFontWeight: getNumericFontWeight(this.fontWeight),
fontVariationSettings: this.fontVariationSettings,
isBold: this.isBold,
isItalic: this.isItalic,
Expand All @@ -114,6 +123,17 @@ export class Font extends FontBase {
}
}

function getNumericFontWeight(weight: FontWeightType): number {
if (weight == null || weight === FontWeight.NORMAL) {
return 400;
}
if (weight === FontWeight.BOLD) {
return 700;
}
const numeric = Number(weight);
return Number.isFinite(numeric) ? numeric : 400;
}

function getNativeFontWeight(fontWeight: FontWeightType): number {
const value = typeof fontWeight === 'number' ? fontWeight + '' : fontWeight;

Expand Down
Loading