Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Manually select font size for text in shapes #544

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
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
33 changes: 17 additions & 16 deletions docs/model/crdt-documents.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,22 +119,23 @@ An Element that has a shape attached, that has a text and a fill color.

#### Fields

| Field | Type | Description |
| --------------- | ---------------------------------------------------- | ------------------------------------------------------------- |
| `type` | `'shape'` | Identifies the element as a shape. |
| `kind` | `'rectangle' \| 'circle' \| 'ellipse' \| 'triangle'` | The kind of shape, defining its look. |
| `position` | `Point` | The position of the shape on the whiteboard canvas. |
| `width` | `number` | Scaling of the shape on the x-axis. |
| `height` | `number` | Scaling of the shape on the y-axis. |
| `fillColor` | `string` | The fill color of the shape as [CSS color value][csscolor]. |
| `strokeColor` | `string \| undefined` | The border color of the shape as [CSS color value][csscolor]. |
| `strokeWidth` | `number \| undefined` | The border width of the shape in pixels. |
| `borderRadius` | `number \| undefined` | The border radius of the shape in pixels. |
| `text` | `YText` / `string` | Text that is displayed in the shape. |
| `textAlignment` | `'left' \| 'center' \| 'right' \| undefined` | The alignment of the text in the shape. |
| `textColor` | `string \| undefined` | The text color of the shape as [CSS color value][csscolor]. |
| `textBold` | `boolean \| undefined` | Should the text have a bold formatting? |
| `textItalic` | `boolean \| undefined` | Should the text have an italic formatting? |
| Field | Type | Description |
| --------------- | ---------------------------------------------------- | ------------------------------------------------------------------------ |
| `type` | `'shape'` | Identifies the element as a shape. |
| `kind` | `'rectangle' \| 'circle' \| 'ellipse' \| 'triangle'` | The kind of shape, defining its look. |
| `position` | `Point` | The position of the shape on the whiteboard canvas. |
| `width` | `number` | Scaling of the shape on the x-axis. |
| `height` | `number` | Scaling of the shape on the y-axis. |
| `fillColor` | `string` | The fill color of the shape as [CSS color value][csscolor]. |
| `strokeColor` | `string \| undefined` | The border color of the shape as [CSS color value][csscolor]. |
| `strokeWidth` | `number \| undefined` | The border width of the shape in pixels. |
| `borderRadius` | `number \| undefined` | The border radius of the shape in pixels. |
| `text` | `YText` / `string` | Text that is displayed in the shape. |
| `textAlignment` | `'left' \| 'center' \| 'right' \| undefined` | The alignment of the text in the shape. |
| `textColor` | `string \| undefined` | The text color of the shape as [CSS color value][csscolor]. |
| `textBold` | `boolean \| undefined` | Should the text have a bold formatting? |
| `textItalic` | `boolean \| undefined` | Should the text have an italic formatting? |
| `textSize` | `number \| undefined` | Font size of the text in CSS pixel unit. `undefined` for auto text size. |

#### Example

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,12 @@ describe('<ElementBar/>', () => {

const toolbar = screen.getByRole('toolbar', { name: 'Element' });

expect(
within(toolbar).getByRole('combobox', {
name: 'Select font size',
}),
).toBeInTheDocument();

expect(
within(toolbar).getByRole('button', {
name: 'Pick a text color',
Expand Down
2 changes: 2 additions & 0 deletions packages/react-sdk/src/components/ElementBar/ElementBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { ElementColorPicker } from './ColorPickerButton/ElementColorPicker';
import { TextColorPicker } from './ColorPickerButton/TextColorPicker';
import { DeleteActiveElementButton } from './DeleteActiveElementButton/DeleteActiveElementButton';
import { DuplicateActiveElementButton } from './DuplicateActiveElementButton';
import { FontSizeButton } from './FontSizeButton';
import { TextAlignmentButtons } from './TextAlignmentButtons';
import { TextBoldButton } from './TextBoldButton';
import { TextItalicButton } from './TextItalicButton';
Expand All @@ -30,6 +31,7 @@ export function ElementBar() {

return (
<Toolbar aria-label={toolbarTitle}>
<FontSizeButton />
<TextBoldButton />
<TextItalicButton />
<TextColorPicker />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
* Copyright 2024 Nordeck IT + Consulting GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { MenuItem, Select } from '@mui/material';
import { useTranslation } from 'react-i18next';
import { useFontSize } from '../../../lib/text-formatting';
import { useActiveElements, useElements } from '../../../state';

const FONT_SIZES = [8, 16, 24, 32, 48, 64, 96, 128, 160, 192];

export function FontSizeButton() {
const { t } = useTranslation('neoboard');
const { fontSize, setFontSize } = useFontSize();

const { activeElementIds } = useActiveElements();
const activeElements = useElements(activeElementIds);
const elements = Object.values(activeElements);

if (elements.every((element) => element.type !== 'shape')) {
return null;
}

return (
<Select
size="small"
variant="standard"
disableUnderline={true}
value={fontSize ?? 'auto'}
inputProps={{
'aria-label': t('elementBar.fontSize', 'Select font size'),
}}
SelectDisplayProps={{
style: {
textAlign: 'center',
paddingRight: '18px',
paddingTop: '4px',
},
}}
onChange={(event) => {
setFontSize(
event.target.value === 'auto'
? undefined
: (event.target.value as number),
);
}}
sx={{
// Set a min-width to prevent change of the select width depending on the value
minWidth: '64px',
padding: '0 5px 0 8px',
}}
>
<MenuItem value="auto">auto</MenuItem>
{FONT_SIZES.map((fontSize) => (
<MenuItem value={fontSize} key={fontSize}>
{fontSize}
</MenuItem>
))}
</Select>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/*
* Copyright 2024 Nordeck IT + Consulting GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

export { FontSizeButton } from './FontSizeButton';
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ export type TextEditorProps = {
onBlur: DispatchWithoutAction;
width: number;
height: number;
fontSize?: number;
editModeOnMount: boolean;
};

Expand All @@ -121,6 +122,7 @@ export function TextEditor({
onBlur,
width,
height,
fontSize,
editModeOnMount = false,
}: TextEditorProps) {
const textRef = useRef<HTMLDivElement>(null);
Expand Down Expand Up @@ -172,10 +174,10 @@ export function TextEditor({
// as part of this keystroke.
window.requestAnimationFrame(() => {
if (textRef.current) {
fitText(textRef.current, contentBold, contentItalic);
fitText(textRef.current, fontSize, contentBold, contentItalic);
}
});
}, [contentBold, contentItalic, textRef]);
}, [fontSize, contentBold, contentItalic, textRef]);

const handleKeyUp = useCallback(() => {
if (textRef.current) {
Expand Down Expand Up @@ -219,11 +221,12 @@ export function TextEditor({
useLayoutEffect(() => {
// Every time content or the shape changes, re-calculate the perfect font size
if (textRef.current) {
fitText(textRef.current, contentBold, contentItalic);
fitText(textRef.current, fontSize, contentBold, contentItalic);
}
}, [
textRef,
content,
fontSize,
contentBold,
contentItalic,
// Width, height, and fontsLoaded are used to trigger calculating the size
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ export type TextElementProps = {
fillColor: string;
elementId: string;
textColor?: string;
fontSize?: number;
};

export const TextElement = ({
Expand All @@ -64,6 +65,7 @@ export const TextElement = ({
fillColor,
elementId,
textColor,
fontSize,
}: TextElementProps) => {
const slideInstance = useWhiteboardSlideInstance();
const [unsubmittedText, setUnsubmittedText] = useState(text);
Expand Down Expand Up @@ -111,6 +113,7 @@ export const TextElement = ({
onChange={handleTextChange}
height={height}
width={width}
fontSize={fontSize}
/>
</ForeignObjectNoInteraction>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,11 +158,22 @@ describe('fitText', () => {
'799px': [0, 0],
});

fitText(container, undefined, fontStyleItalic);
fitText(container, undefined, undefined, fontStyleItalic);

expect(container.style.padding).toEqual(expectedPadding);
},
);

it('should set a static font size', () => {
const container = createContainerElement(500, 500, {
'405px': [0, 0],
});

fitText(container, 23);

expect(container.style.flexBasis).toBe('');
expect(container.style.fontSize).toBe('23px');
});
});

function createContainerElement(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,26 +22,32 @@ const maxSteps = 10;

export function fitText(
element: HTMLElement,
fontSize?: number,
fontWeightBold = false,
fontStyleItalic = false,
) {
const width = element.clientWidth;
const height = element.clientHeight;

const { fontSize, paddingTop, paddingHorizontal } = getTextSize(
const {
fontSize: actualSize,
paddingTop,
paddingHorizontal,
} = getTextSize(
width,
height,
{
innerHTML: element.innerHTML,
innerText: element.innerText,
},
{
fontSize,
fontWeightBold,
fontStyleItalic,
},
);

element.style.fontSize = `${fontSize}px`;
element.style.fontSize = `${actualSize}px`;
element.style.padding = `${paddingTop}px ${paddingHorizontal}em 0`;
}

Expand Down Expand Up @@ -86,6 +92,7 @@ export function getTextSize(
content: { innerHTML?: string; innerText: string },
opts: {
disableLigatures?: boolean;
fontSize?: number;
fontFamily?: string;
fontWeightBold?: boolean;
fontStyleItalic?: boolean;
Expand All @@ -100,7 +107,13 @@ export function getTextSize(

const { textElement: element, wrapperElement } = getTemporaryElement();

wrapperElement.style.flexBasis = `${width}px`;
if (opts.fontSize === undefined) {
wrapperElement.style.flexBasis = `${width}px`;
wrapperElement.style.width = 'unset';
} else {
wrapperElement.style.flexBasis = 'unset';
wrapperElement.style.width = `${width}px`;
}

element.style.lineHeight = '1.2';
element.style.wordBreak = 'unset';
Expand All @@ -124,28 +137,33 @@ export function getTextSize(
const paddingHorizontal = opts.fontStyleItalic ? 0.2 : 0;
element.style.padding = `0 ${paddingHorizontal}em`;

// Do a binary search to find the best matching text size, in a few steps
let stepSize = maxFontSize - minFontSize;
let fontSize = minFontSize;
let fontSize: number;
if (opts.fontSize !== undefined) {
fontSize = opts.fontSize;
} else {
// Do a binary search to find the best matching text size, in a few steps
let stepSize = maxFontSize - minFontSize;
fontSize = minFontSize;

for (let i = 0; i < maxSteps; ++i) {
const lastFontSize = fontSize;
stepSize /= 2;
fontSize = clamp(fontSize + stepSize, minFontSize, maxFontSize);
for (let i = 0; i < maxSteps; ++i) {
const lastFontSize = fontSize;
stepSize /= 2;
fontSize = clamp(fontSize + stepSize, minFontSize, maxFontSize);

element.style.fontSize = `${Math.round(fontSize)}px`;
element.style.fontSize = `${Math.round(fontSize)}px`;

const { width: scrollWidth, height: scrollHeight } =
element.getBoundingClientRect();
const { width: scrollWidth, height: scrollHeight } =
element.getBoundingClientRect();

const fits = scrollWidth <= width && scrollHeight <= height;
const fits = scrollWidth <= width && scrollHeight <= height;

if (!fits) {
fontSize = lastFontSize;
if (!fits) {
fontSize = lastFontSize;
}
}
}

fontSize = Math.round(fontSize);
fontSize = Math.round(fontSize);
}

element.style.fontSize = `${fontSize}px`;

Expand Down
1 change: 1 addition & 0 deletions packages/react-sdk/src/components/Whiteboard/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,5 +36,6 @@ export type ElementRenderProperties = {
alignment: TextAlignment;
bold: boolean;
italic: boolean;
fontSize?: number;
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ const EllipseDisplay = ({
width={text.width}
height={text.height}
fillColor={shape.fillColor}
fontSize={text.fontSize}
/>
)}
</g>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export function getRenderProperties(
alignment: shape.textAlignment ?? 'center',
bold: shape.textBold ?? false,
italic: shape.textItalic ?? false,
fontSize: shape.textSize,
},
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ const RectangleDisplay = ({
height={text.height}
fillColor={shape.fillColor}
textColor={shape.textColor}
fontSize={text.fontSize}
/>
)}
</g>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export function getRenderProperties(
alignment: shape.textAlignment ?? 'center',
bold: shape.textBold ?? false,
italic: shape.textItalic ?? false,
fontSize: shape.textSize,
},
};
}
Loading