Skip to content

[dev-v5] fluent-text-suggestion Web Component #3129

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

Draft
wants to merge 10 commits into
base: dev-v5
Choose a base branch
from
Draft
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
34 changes: 30 additions & 4 deletions examples/Demo/FluentUI.Demo.Client/DebugPages/Test.razor
Original file line number Diff line number Diff line change
@@ -1,10 +1,36 @@
@page "/Debug/Test"
<h3>Test</h3>

<fluent-text-input />
<br/>

<InputText @bind-Value="@test" />
<fluent-text-input id="my-field" />
<fluent-text-suggestion anchor="my-field" shadowQuerySelector="input[id='control']" value="abc" />
<br />

<fluent-textarea id="my-field-area" />
<fluent-text-suggestion anchor="my-field-area" shadowQuerySelector="textarea[id='control']" value="abc" />
<br />

@code {
public string test { get; set; } = "test";
}
<input type="text" id="my-text" />
<fluent-text-suggestion anchor="my-text" value="abc" />
<br />

<textarea id="my-area" spellcheck="false" />
<fluent-text-suggestion anchor="my-area" value="abc" minlength="3" delay="10" />
<br />

<script>
setInterval(() => {
updateAttribute("my-field");
updateAttribute("my-field-area");
updateAttribute("my-text");
updateAttribute("my-area");
}, 2000);

function updateAttribute(anchor) {
const element = document.querySelector(`fluent-text-suggestion[anchor="${anchor}"]`);
const newValue = element.getAttribute("value") === 'abc' ? 'def' : 'abc';
element.value = newValue;
}
</script>
137 changes: 68 additions & 69 deletions src/Core.Scripts/src/Components/PageScript/FluentPageScript.ts
Original file line number Diff line number Diff line change
@@ -1,96 +1,95 @@
import { StartedMode } from "../../d-ts/StartedMode";

export namespace Microsoft.FluentUI.Blazor.Components.PageScript {
const pageScriptInfoBySrc = new Map();

const pageScriptInfoBySrc = new Map();
export class FluentPageScript extends HTMLElement {
static observedAttributes = ['src'];
src: string | null = null;

export class FluentPageScript extends HTMLElement {
static observedAttributes = ['src'];
src: string | null = null;

attributeChangedCallback(name: string | null, oldValue: string | null, newValue: string | null): void {
if (name !== 'src') {
return;
}

this.src = newValue;
this.unregisterPageScriptElement(oldValue);
this.registerPageScriptElement(newValue);
/**
* Register the FluentPageScript component
* @param blazor
* @param mode
*/
public static registerComponent = (blazor: Blazor, mode: StartedMode): void => {
if (typeof blazor.addEventListener === 'function' && mode === StartedMode.Web) {
customElements.define('fluent-page-script', FluentPageScript);
blazor.addEventListener('enhancedload', onEnhancedLoad);
}
};

disconnectedCallback(): void {
this.unregisterPageScriptElement(this.src);
attributeChangedCallback(name: string | null, oldValue: string | null, newValue: string | null): void {
if (name !== 'src') {
return;
}

registerPageScriptElement(src: string | null): void {
if (!src) {
throw new Error('Must provide a non-empty value for the "src" attribute.');
}
this.src = newValue;
this.unregisterPageScriptElement(oldValue);
this.registerPageScriptElement(newValue);
}

let pageScriptInfo = pageScriptInfoBySrc.get(src);
disconnectedCallback(): void {
this.unregisterPageScriptElement(this.src);
}

if (pageScriptInfo) {
pageScriptInfo.referenceCount++;
} else {
pageScriptInfo = { referenceCount: 1, module: null };
pageScriptInfoBySrc.set(src, pageScriptInfo);
this.initializePageScriptModule(src, pageScriptInfo);
}
registerPageScriptElement(src: string | null): void {
if (!src) {
throw new Error('Must provide a non-empty value for the "src" attribute.');
}

unregisterPageScriptElement(src: string | null): void {
if (!src) {
return;
}

const pageScriptInfo = pageScriptInfoBySrc.get(src);
if (!pageScriptInfo) {
return;
}
let pageScriptInfo = pageScriptInfoBySrc.get(src);

pageScriptInfo.referenceCount--;
if (pageScriptInfo) {
pageScriptInfo.referenceCount++;
} else {
pageScriptInfo = { referenceCount: 1, module: null };
pageScriptInfoBySrc.set(src, pageScriptInfo);
this.initializePageScriptModule(src, pageScriptInfo);
}
}

async initializePageScriptModule(src: string, pageScriptInfo: any): void {
if (src.startsWith("./")) {
src = new URL(src.substring(2), document.baseURI).toString();
}

const module = await import(src);

if (pageScriptInfo.referenceCount <= 0) {
return;
}
unregisterPageScriptElement(src: string | null): void {
if (!src) {
return;
}

pageScriptInfo.module = module;
module.onLoad?.();
module.onUpdate?.();
const pageScriptInfo = pageScriptInfoBySrc.get(src);
if (!pageScriptInfo) {
return;
}

pageScriptInfo.referenceCount--;
}

const onEnhancedLoad = (): void => {
for (const [src, { module, referenceCount }] of pageScriptInfoBySrc) {
if (referenceCount <= 0) {
module?.onDispose?.();
pageScriptInfoBySrc.delete(src);
}
async initializePageScriptModule(src: string, pageScriptInfo: any): void {
if (src.startsWith("./")) {
src = new URL(src.substring(2), document.baseURI).toString();
}

for (const { module } of pageScriptInfoBySrc.values()) {
module?.onUpdate?.();
const module = await import(src);

if (pageScriptInfo.referenceCount <= 0) {
return;
}

pageScriptInfo.module = module;
module.onLoad?.();
module.onUpdate?.();
}
}

/**
* Register the FluentPageScript component
* @param blazor
* @param mode
*/
export const registerComponent = (blazor: Blazor, mode: StartedMode): void => {
if (typeof blazor.addEventListener === 'function' && mode === StartedMode.Web) {
customElements.define('fluent-page-script', FluentPageScript);
blazor.addEventListener('enhancedload', onEnhancedLoad);
const onEnhancedLoad = (): void => {
for (const [src, { module, referenceCount }] of pageScriptInfoBySrc) {
if (referenceCount <= 0) {
module?.onDispose?.();
pageScriptInfoBySrc.delete(src);
}
};
}

for (const { module } of pageScriptInfoBySrc.values()) {
module?.onUpdate?.();
}
}



154 changes: 154 additions & 0 deletions src/Core.Scripts/src/Components/TextSuggestion/Caret-xy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
/*
Original source from https://github.com/tnhu/caret-xy
*/

const root = document.documentElement
const body = document.body
let remToPixelRatio: any

export interface CaretPosition {
top: number
left: number
height: number
}

function toPixels(value: any, elementFontSize: any) {
var pixels = parseFloat(value)

if (value.indexOf('pt') !== -1) {
pixels = pixels * 4 / 3
} else if (value.indexOf('mm') !== -1) {
pixels = pixels * 96 / 25.4
} else if (value.indexOf('cm') !== -1) {
pixels = pixels * 96 / 2.54
} else if (value.indexOf('in') !== -1) {
pixels *= 96
} else if (value.indexOf('pc') !== -1) {
pixels *= 16
} else if (value.indexOf('rem') !== -1) {
if (!remToPixelRatio) {
remToPixelRatio = parseFloat(getComputedStyle(root).fontSize)
}
pixels *= remToPixelRatio
} else if (value.indexOf('em') !== -1) {
pixels = elementFontSize ? pixels * parseFloat(elementFontSize) : toPixels(pixels + 'rem', elementFontSize)
}

return pixels
}

function lineHeightInPixels(lineHeight: any, elementFontSize: any) {
return lineHeight === 'normal' ? 1.2 * parseInt(elementFontSize, 10) : toPixels(lineHeight, elementFontSize)
}

// Original source from `textarea-caret-position`
// https://github.com/component/textarea-caret-position
// MIT, Copyright (c) 2015 Jonathan Ong [email protected]

// The attributes that we copy into a mirrored div.
// Note that some browsers, such as Firefox,
// do not concatenate properties, i.e. padding-top, bottom etc. -> padding,
// so we have to do every single property specifically.
const mirrorAttributes = [
'direction', // RTL support
'boxSizing',
'width', // on Chrome and IE, exclude the scrollbar, so the mirror div wraps exactly as the textarea does
'height',
'overflowX',
'overflowY', // copy the scrollbar for IE

'borderTopWidth',
'borderRightWidth',
'borderBottomWidth',
'borderLeftWidth',
'borderStyle',

'paddingTop',
'paddingRight',
'paddingBottom',
'paddingLeft',

// https://developer.mozilla.org/en-US/docs/Web/CSS/font
'fontStyle',
'fontVariant',
'fontWeight',
'fontStretch',
'fontSize',
'fontSizeAdjust',
'lineHeight',
'fontFamily',

'textAlign',
'textTransform',
'textIndent',
'textDecoration', // might not make a difference, but better be safe

'varterSpacing',
'wordSpacing',

'tabSize',
'MozTabSize'
]

function getMirrorInfo(element: any, isInput: any) {
if (element.mirrorInfo) {
return element.mirrorInfo
}

const div = document.createElement('div')
const style: any = div.style
const computedStyles: any = getComputedStyle(element)
const hidden = 'hidden'
const focusOut = 'focusout'

style.whiteSpace = 'pre-wrap'
if (!isInput) style.wordWrap = 'break-word' // only for textarea

style.position = 'absolute'
style.visibility = hidden // not 'display: none' because we want rendering

mirrorAttributes.forEach(prop => style[prop] = computedStyles[prop])
style.overflow = hidden // Do we need to copy overflowX, overflowY if this is set?

if (isInput) {
style.whiteSpace = 'nowrap'
}

body.appendChild(div)

// Cache mirror info so we don't create elements and invoke getComputedStyle() again and again
element.mirrorInfo = { div, span: document.createElement('span'), computedStyles }

// Remove cached mirror div when element is out of focus
element.addEventListener(focusOut, function cleanup() {
delete element.mirrorInfo
body.removeChild(div)
element.removeEventListener(focusOut, cleanup)
})

return element.mirrorInfo
}

export default function caretXY(element: any, position = element.selectionEnd): CaretPosition {
const isInput = element.nodeName.toLowerCase() === 'input'
const { div, span, computedStyles } = getMirrorInfo(element, isInput)
const content = element.value.substring(0, position)

// For input, text content needs to be replaced with non-breaking spaces - http://stackoverflow.com/a/13402035/1269037
div.textContent = isInput ? content.replace(/\s/g, '\u00a0') : content

// Wrapping must be replicated *exactly*, including when a long word gets
// onto the next line, with whitespace at the end of the line before (#7).
// The *only* reliable way to do that is to copy the *entire* rest of the
// textarea content into the <span> created at the caret position.
// for inputs, just '.' would be enough, but why bother?
span.textContent = element.value.substring(position) || '.' // || because a completely empty faux span doesn't render at all
div.appendChild(span)

const rect = element.getBoundingClientRect()
const top = span.offsetTop + parseInt(computedStyles.borderTopWidth) - element.scrollTop + rect.top
const left = span.offsetLeft + parseInt(computedStyles.borderLeftWidth) - element.scrollLeft + rect.left
const height = lineHeightInPixels(computedStyles.lineHeight, computedStyles.fontSize)

return { top, left, height }
}
38 changes: 38 additions & 0 deletions src/Core.Scripts/src/Components/TextSuggestion/CaretUtil.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import caretXY from "./Caret-xy";

export function scrollTextAreaDownToCaretIfNeeded(textArea: HTMLTextAreaElement | HTMLInputElement) {
// Note that this only scrolls *down*, because that's the only scenario after a suggestion is accepted
const pos = caretXY(textArea);
const lineHeightInPixels = parseFloat(window.getComputedStyle(textArea).lineHeight);
if (pos.top > textArea.clientHeight + textArea.scrollTop - lineHeightInPixels) {
textArea.scrollTop = pos.top - textArea.clientHeight + lineHeightInPixels;
}
}

export function getCaretOffsetFromOffsetParent(elem: HTMLTextAreaElement | HTMLInputElement): { top: number, left: number, height: number, elemStyle: CSSStyleDeclaration } {
const elemStyle = window.getComputedStyle(elem);
const pos = caretXY(elem);

return {
top: pos.top, // + parseFloat(elemStyle.borderTopWidth) + elem.offsetTop - elem.scrollTop,
left: pos.left, // + parseFloat(elemStyle.borderLeftWidth) + elem.offsetLeft - elem.scrollLeft - 0.25,
height: pos.height,
elemStyle: elemStyle,
}
}

export function insertTextAtCaretPosition(textArea: HTMLTextAreaElement | HTMLInputElement, text: string) {
// Even though document.execCommand is deprecated, it's still the best way to insert text, because it's
// the only way that interacts correctly with the undo buffer. If we have to fall back on mutating
// the .value property directly, it works but erases the undo buffer.
if (document.execCommand) {
document.execCommand('insertText', false, text);
} else {
let caretPos = textArea.selectionStart ?? 0;
textArea.value = textArea.value.substring(0, caretPos)
+ text
+ textArea.value.substring(textArea.selectionEnd ?? 0);
caretPos += text.length;
textArea.setSelectionRange(caretPos, caretPos);
}
}
Loading