How to use mobx-utils - 10 common examples

To help you get started, we’ve selected a few mobx-utils examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github eez-open / studio / packages / project-editor / project / build.ts View on Github external
OutputSectionsStore.write(Section.OUTPUT, Type.ERROR, err.message, err.object);
        } else {
            OutputSectionsStore.write(Section.OUTPUT, Type.ERROR, `Module build error: ${err}`);
        }

        showCheckResult();
    } finally {
        OutputSectionsStore.setLoading(Section.OUTPUT, false);
    }

    console.log("Build time:", new Date().getTime() - timeStart);
}

////////////////////////////////////////////////////////////////////////////////

var checkTransformer: (object: EezObject) => IMessage[] = createTransformer(
    (object: EezObject): IMessage[] => {
        let messages: IMessage[] = [];

        // call check method of the object
        if ((object as any).check) {
            messages = messages.concat((object as any).check());
        }

        // call check from property definition
        if (object._propertyInfo && object._propertyInfo.check) {
            messages = messages.concat(object._propertyInfo.check(object));
        }

        if (isArray(object)) {
            // check array elements
            for (const childObject of asArray(object)) {
github OpenZeppelin / crafty / app / src / util.js View on Github external
export const createFromEthereumBlock = (blockNumber) => (initial, dataFn, fn) => {
  let disposer
  let isBusy = observable.box(false)
  const resource = fromResource(
    (sink) => {
      disposer = reaction(
        () => [dataFn(), blockNumber],
        async ([data]) => {
          try {
            runInAction(() => isBusy.set(true))
            sink(await fn(data))
          } catch (error) {
            // @TODO(handle errors)
            console.error(error)
            debugger
          } finally {
            runInAction(() => isBusy.set(false))
          }
        },
        { fireImmediately: true }
github NUbots / NUsight2 / src / client / components / localisation / utils.ts View on Github external
}
    },
  }
}

const coloredMaterial = (material: Material, color?: string) => {
  if (material instanceof MeshLambertMaterial && material.name === 'Plastic' && color) {
    const newMaterial = material.clone()
    newMaterial.color.lerp(new Color(color), 0.5)
    return newMaterial
  } else {
    return material
  }
}

const parseConfig = createTransformer((config: any) => {
  const { geometry, materials } = new LegacyJSONLoader().parse(config, '/')
  // Compute vertex normals with a crease angle of 0.52
  computeVertexNormals(geometry, 0.52)
  return { geometry, materials }
})

/**
 * Drew's crease angle computeVertexNormals function for the darwin
 *
 * @author Drew Noakes http://drewnoakes.com
 */
function computeVertexNormals(geometry: Geometry, maxSmoothAngle: number) {
  const faceIndicesPerVertex: number[][] = []
  for (let v = 0, vl = geometry.vertices.length; v < vl; v++) {
    faceIndicesPerVertex.push([])
  }
github tpucci / react-nonav / src / createCanal.tsx View on Github external
isAuthorized:
              /**
               * @TODO 19-06-01 Check if Authorization type can be indexed with StopName type.
               * See https://github.com/Microsoft/TypeScript/issues/2491.
               */
              // @ts-ignore
              !!authorizations[name] && (last(acc) ? last(acc).isAuthorized : true),
            isFullScreen,
            name,
          });
          return acc;
        }, [])
      )
    );

    stack = fromStream(
      this.progress$.pipe(
        map(progressStopsList => progressStopsList.filter(stop => !stop.isFullScreen))
      ),
      []
    );

    fullScreenStackProperties$ = this.progress$.pipe(
      map(progressStopsList => ({
        canalId: this.canalId,
        fullScreenStack: progressStopsList.filter(stop => stop.isFullScreen),
      })),
      distinctUntilChanged(
        ({ fullScreenStack: previousFullScreenStack }, { fullScreenStack: nextFullScreenStack }) =>
          previousFullScreenStack.filter(stop => stop.isAuthorized).length ===
          nextFullScreenStack.filter(stop => stop.isAuthorized).length
      )
github PacktPublishing / MobX-Quick-Start-Guide / src / Chapter08 / createViewModel.js View on Github external
export const CreateViewModelExample = asComponent(() => {
    class FormData {
        @observable name = '';
        @observable email = '';
        @observable favoriteColor = '';
    }

    const viewModel = createViewModel(new FormData());

    autorun(() => {
        console.log(
            `ViewModel: ${viewModel.name}, Model: ${
                viewModel.model.name
            }, Dirty: ${viewModel.isDirty}`,
        );
    });

    viewModel.name = 'Pavan';
    viewModel.email = 'pavan@pixelingene.com';
    viewModel.favoriteColor = 'orange';

    console.log('About to reset...');
    viewModel.reset();
github NUbots / NUsight2 / src / client / components / script_tuner / model_visualiser / darwin_robot / head / view_model.ts View on Github external
mesh.add(createCamera(viewModel.color))

  return mesh
})

const createHeadLED = createTransformer((color?: string) => {
  const { geometry, materials } = geometryAndMaterial(HeadLEDConfig, color)
  return new Mesh(geometry, materials)
})

const createEyeLED = createTransformer((color?: string) => {
  const { geometry, materials } = geometryAndMaterial(EyeLEDConfig, color)
  return new Mesh(geometry, materials)
})

const createCamera = createTransformer((color?: string) => {
  const { geometry, materials } = geometryAndMaterial(CameraConfig, color)
  return new Mesh(geometry, materials)
})
github NUbots / NUsight2 / src / client / components / script_tuner / model_visualiser / darwin_robot / head / view_model.ts View on Github external
import { createTransformer } from 'mobx-utils'
import { Mesh } from 'three'
import { Object3D } from 'three'

import { geometryAndMaterial } from '../../../utils'
import { Robot3dViewModel } from '../../model'

import * as CameraConfig from './config/camera.json'
import * as EyeLEDConfig from './config/eye_led.json'
import * as HeadConfig from './config/head.json'
import * as HeadLEDConfig from './config/head_led.json'
import * as NeckConfig from './config/neck.json'

export const createHead = createTransformer((viewModel: Robot3dViewModel) => {
  const head = new Object3D()
  head.add(createNeck(viewModel))
  return head
})

const createNeck = createTransformer((viewModel: Robot3dViewModel) => {
  const { geometry, materials } = geometryAndMaterial(NeckConfig, viewModel.color)
  const mesh = new Mesh(geometry, materials)

  mesh.position.set(0, 0.051, 0)
  mesh.rotation.set(0, viewModel.HEAD_YAW, 0)
  mesh.add(createSkull(viewModel))

  return mesh
})
github TerriaJS / terriajs / lib / ModelMixins / TableMixin.ts View on Github external
const table = this.dataColumnMajor;
      if (table === undefined) {
        return [];
      }

      const columnTraits = this.columns || [];
      return table.map(tableColumn => {
        const columnName = tableColumn[0];
        return (
          columnTraits.find(traits => traits.name === columnName) ||
          createStratumInstance(TableColumnTraits)
        );
      });
    }

    private readonly getTableColumn = createTransformer((index: number) => {
      return new TableColumn(this, index);
    });
  }

  return TableMixin;
}
github gotify / server / ui / src / message / MessagesStore.ts View on Github external
};

    private getUnCached = (appId: number): Array => {
        const appToImage = this.appStore
            .getItems()
            .reduce((all, app) => ({...all, [app.id]: app.image}), {});

        return this.stateOf(appId, false).messages.map((message: IMessage) => {
            return {
                ...message,
                image: appToImage[message.appid] || null,
            };
        });
    };

    public get = createTransformer(this.getUnCached);

    private clearCache = () => (this.get = createTransformer(this.getUnCached));

    private createEmptyStatesForApps = (apps: IApplication[]) => {
        apps.map((app) => app.id).forEach((id) => this.stateOf(id, /*create*/ true));
        this.clearCache();
    };

    private emptyState = (): MessagesState => ({
        messages: observable.array(),
        hasMore: true,
        nextSince: 0,
        loaded: false,
    });
}
github NUbots / NUsight2 / src / client / render2d / pixi / rendering.ts View on Github external
import { PolygonGeometry } from '../geometry/polygon_geometry'
import { TextGeometry } from '../geometry/text_geometry'
import { Geometry } from '../object/geometry'
import { Group } from '../object/group'
import { Shape } from '../object/shape'

import { renderArc } from './arc'
import { renderArrow } from './arrow'
import { renderCircle } from './circle'
import { renderLine } from './line'
import { renderMarker } from './marker'
import { renderPath } from './path'
import { renderPolygon } from './polygon'
import { renderText } from './text'

export const pixiObject = createTransformer((obj: Group | Shape): DisplayObject => {

  if (obj instanceof Group) {
    const g = new Container()

    const { transform: { scale, translate, rotate } } = obj
    g.scale.x = scale.x
    g.scale.y = scale.x
    g.x = translate.x
    g.y = translate.y
    g.rotation = rotate

    obj.children.forEach(o => {
      g.addChild(pixiObject(o))
    })

    return g